Copying rows from another table in MySQL

Discussion in 'PHP' started by Connor Beaton, Jun 25, 2009.

  1. #1
    Hey,

    I need to make a query to pull the fields id and game from table A and insert them as media_id and game_id in table B, but only if the field game is not empty. I also need to insert 'news' into the field media_type in table B.

    How can I achieve this?

    Thanks,
    Connor Beaton
     
    Connor Beaton, Jun 25, 2009 IP
  2. Wrighty

    Wrighty Peon

    Messages:
    199
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    <?PHP
    
    $sql = mysql_query("SELECT * FROM `Table A` WHERE `game` != ''");
    while($row = mysql_fetch_assoc($sql)){
    mysql_query("INSERT INTO `Table B` (`media_id`, `game_id`, `media_type`) VALUES ('" . $row['id'] . "', '" . $row['game'] . "', 'news')");
    }
    
    ?>
    Code (markup):

    :)
     
    Wrighty, Jun 25, 2009 IP
  3. Connor Beaton

    Connor Beaton Peon

    Messages:
    24
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks mate, you're a legend. Worked a charm. :)
     
    Connor Beaton, Jun 25, 2009 IP
  4. Wrighty

    Wrighty Peon

    Messages:
    199
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Glad to help! :)

    Let me know if you need anything more.
     
    Wrighty, Jun 25, 2009 IP
  5. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #5
    You can also run this as a single query as long as 'news' doesn't need to be unique per insert.

    INSERT INTO table_b (media_id, game_id, media_type) SELECT (id, game, 'news') FROM table_a WHERE game != '';
     
    jestep, Jun 25, 2009 IP
  6. franklyn

    franklyn Peon

    Messages:
    26
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    I'd rather do that ^ instead , so you don't have to send multiple queries to the DB. It's probably better optimized aswell.
     
    franklyn, Jun 25, 2009 IP