简体   繁体   中英

How to join three tables and display the result?

I am trying to understand how to join and display data from three tables and have created these three that list person (person) , types of fruit (fruit) and the fruit the people like (favs) .

 Person               Fruit                 Favs

id  |  name        id  | type        id |  person_id  |  fruit_id

1   |  Peter        1  | apple       1  |  Peter      |  orange
2   |  Sue          2  | orange      2  |  Sue        |  apple
3   |  John         3  | banana      3  |  John       |  banana
4   |  Mary                          4  |  Peter      |  apple
                                     5  |  Sue        |  orange

My aim is to learn how to join all three tables and display which fruits (if any) the people like. Just like this:

Peter  | orange, apple
Sue    | apple, orange
John   | banana
Mary   |

I just about understand how to join all three tables to display the data above but the thing that really confuses me is how to echo out the results. Should I be using nested while loops or a foreeach loop? I've got so confused and would really appreciate someone showing me the way. The closest I've got is this (which is far off I know).

<?php

$sql="SELECT person.name, favs.fruit_id 
      FROM person LEFT JOIN favs
      ON person.name = favs.person_id
      ORDER by person.id";

$result_set=mysql_query($sql);

while($row=mysql_fetch_array($result_set))
{
    echo $row['name'];
    echo $row['fruit_id'];
    echo '<br />';
}

Ok in your table example data, I assume in table Favs you placed the names for readability, wouldn't it be the IDs themselves. Assuming that is the case using the GROUP_CAT your SQL statement would be:

SELECT p.name, GROUP_CONCAT(ft.name)
FROM favs f
INNER JOIN fruit ft ON ft.id = f.fruit_id
LEFT JOIN person p ON p.id = f.person_id
GROUP BY f.person_id

像这样做:

SELECT Person.id,Fruit.name FROM Person INNER JOIN Person.id=Fruit.person_id WHERE ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM