Getting data from two mysql tables based on id of first table

Discussion in 'PHP' started by phantom, Aug 6, 2010.

  1. #1
    I have two tables like this

    table 1
    id | name | stuff|
    117 |foo |info about foo

    table 2
    id | fooid| comments|
    1 |117 |awesome recipe!
    5 |117 |great taste!
    8 |96 | nice pic!

    I am pretty sure I need to do a left join but I am not sure how to do it by id

    I need to select everything (*) from table 1 based on id and also get everything in table 2 that has fooid the same as id from table 1. But also not fail if there is no match in table 2...ie I still need table 1's data returned regardless.


    Can anyone give me some insight as to how to do this?


    Thanks in advance!
     
    phantom, Aug 6, 2010 IP
  2. themullet

    themullet Member

    Messages:
    110
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    26
    #2
    Would personally do it as 2 queries, otherwise you would end up duping the name and stuff from table 1.

    after selected the stuff from table 1, it's then just a case of where fooid='$res[id]'
     
    themullet, Aug 6, 2010 IP
  3. Alex Roxon

    Alex Roxon Active Member

    Messages:
    424
    Likes Received:
    11
    Best Answers:
    7
    Trophy Points:
    80
    #3
    Single query:
    SELECT *
    FROM `table1`
    LEFT JOIN `table2` ON table1.id = table2.fooid
    GROUP BY table1.id
    Code (markup):
     
    Alex Roxon, Aug 6, 2010 IP