我有两个表:一个,主表显示星期几,当天显示汤。 桌上的汤,有一份可能的汤清单。
+-----+------------+--------+
| id | day |id_soup |
+-----+------------+--------+
| 1 | Friday | 1 |
| 2 | Saturday | 1 |
| 3 | Sunday | 2 |
+-----+------------+--------+
+-----+------------+
| id | soup |
+-----+------------+
| 1 | potatoes |
| 2 | carrots |
| 3 | peas |
+-----+------------+
要获得星期五汤(字符串不是id),我可以使用这样的查询:
SELECT ma.id, ma.day, ma.id_soup, so.soup
FROM main ma, soup so
WHERE ma.id_soup = so.id
AND ma.id = 1
我得到这样的东西(输出)
+-----+------------+---------+----------+
| id | day | id_soup | soup |
+-----+------------+---------+----------+
| 1 | Friday | 1 | potatoes |
+-----+------------+---------+----------+
如果星期五只提供一汤,这种情况很有效。
问题是周五将有两个汤(土豆和豌豆 - 一系列汤)
我们需要另一张桌子吗?
EDITED
+-----+---------+---------+
| id | id_day | id_soup |
+-----+---------+---------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 2 |
| 4 | 2 | 3 |
| 5 | 3 | 1 |
| 6 | 3 | 3 |
+-----+---------+---------+
除了主表(id,day,id_soup)的其他字段,还可以在单个查询中获取汤数组(土豆,豌豆)?
构建此查询的最佳方法是什么?
编辑:
期望的输出(仅用于说明):
+-----+------------+---------+------------------+
| id | day | id_soup | soup |
+-----+------------+---------+------------------+
| 1 | Friday | 1 | potatoes, peas |
+-----+------------+---------+------------------+
EDITED
问题:如果需要的输出如下:
+-----+------------+-------------------+
| id | day | soup |
+-----+------------+---------+---------+
| 1 | Friday | potatoes, carrots |
+-----+------------+---------+---------+
| 2 | Saturday | carrots, peas |
+-----+------------+---------+---------+
| 3 | Sunday | potatoes, peas |
+-----+------------+---------+---------+
答案 0 :(得分:3)
是的,如果每天有多个汤,您将需要一个中间表。
您可以使用GROUP_CONCAT
声明中的SELECT
为所有汤写一天。
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat
SELECT ma.id, ma.day, GROUP_CONCAT(DISTINCT so.soup) as soup
FROM main ma
LEFT JOIN soupmain sm ON(ma.id = sm.id_main)
LEFT JOIN soup so ON(so.id = sm.id_soup)
WHERE ma.id = 1
GROUP BY ma.id
答案 1 :(得分:1)
您可以使用group_concat
SELECT ma.day, groupconcat(so.soup)
FROM main ma, soup so
WHERE ma.id_soup = so.id
AND ma.id = 1
group by ma.day