如何从具有一对多关系的表中选择一行结果


How to select from table with one to many relation to be one row result

我有 2 个表:

餐厅

+---------------+----------------+
| restaurant_id | Restaurant name|
+---------------+----------------+
| 1             | KFC            |
| 2             | McD            |
+----+---------------------------+

+---------------+---------------+----------------+
| cuisine_id    | restaurant_id | cuisine        |
+---------------+---------------+----------------+
| 1             | 1             | Fastfood       |
| 2             | 1             | Fried Chicken  |
| 3             | 2             | Fastfood       |
| 4             | 2             | Burger         |
+---------------+---------------+----------------+

是否有可能获得这样的数据=

+---------------+----------------+------------------------+
| restaurant_id | Restaurant name| Cuisine                |
+---------------+----------------+------------------------+
| 1             | KFC            |Fastfood, Fried Chicken |
| 2             | McD            |Fastfood, Burger        |
+----+---------------------------+------------------------+

使用单个查询?或者我应该通过 php 来做(首先选择 table Restaurant> foreach 循环>按餐厅 id 选择美食>解析到新数组中)。

您可以使用GROUP_CONCAT来实现此目的:

SELECT r.restaurant_id, r.Restaurant_name,
       GROUP_CONCAT(c.cuisine ORDER BY c.cuisine)
FROM Restaurant AS r
LEFT JOIN Cuisine AS c ON r.restaurant_id = c.restaurant_id
GROUP BY  r.restaurant_id, r.Restaurant_name

注意:仅当您想要一个有序的逗号分隔的cuisine名称列表时,才需要GROUP_CONCAT中的ORDER BY子句。

您可以使用

GROUP_CONCAT:

SELECT c.restaurant_id,r.restaurant_name, GROUP_CONCAT(c.cuisine)
FROM Restaurant r
INNER JOIN Cuisine c ON c.restaurant_id = r.restaurant_id 
GROUP BY c.restaurant_id
SELECT Restaurant.restaurant_id, Restaurant.Restaurant_name, GROUP_CONCAT(Cuisine.cuisine)
FROM Restaurant
LEFT JOIN Cuisine ON Restaurant.restaurant_id = Cuisine.restaurant_id
GROUP BY Restaurant.restaurant_id, Restaurant.Restaurant_name