[英]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)
。
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?
我应该使用嵌套的while循环还是foreeach循环? 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. 好的,在您的表示例数据中,我假设您在表收藏夹中放置了用于可读性的名称,不是ID本身。 Assuming that is the case using the GROUP_CAT your SQL statement would be:
假设使用GROUP_CAT是这种情况,那么您的SQL语句将是:
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 ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.