我有这张表:
------------------
| id | foods |
------------------
| 1 | cookies |
| 2 | cake |
| 3 | milk |
------------------
此表:
------------------
| id | colors |
------------------
| 1 | red |
| 1 | blue |
| 1 | pink |
| 2 | orange |
| 2 | yellow |
| 2 | purple |
| 3 | cyan |
| 3 | gold |
| 3 | silver |
------------------
我想从第一张桌子中选择食物,并根据内容与第二张桌子中的颜色进行匹配。
所以我希望输出看起来像这样:
--------------------------------------------
| id | foods | colors |
--------------------------------------------
| 1 | cookies | red, blue, pink |
| 2 | cake | orange, yellow, purple |
| 3 | milk | cyan, gold, silver |
--------------------------------------------
我该怎么做?
编辑:这不是重复。我不想连接。我正在尝试将连接表合并到基于ID的常规表中。
答案 0 :(得分:2)
应该是这样的:
SELECT f.food, GROUP_CONCAT(c.color SEPARATOR ' ') FROM food_table f join color_table c on f.food_id = c.id GROUP BY food;
可在此处找到文档:
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat