MySQL:多行以逗号分隔的单行

时间:2010-08-16 11:04:58

标签: mysql database

我有两张桌子:DISH和DISH_HAS_DISHES。菜桌上有所有的菜肴,“Dish_has_dishes”表与“菜”表有一对多的关系。即一道菜可以有多道菜。例如

DISH

dish_id   dish_name
1         dish_1
2         dish_2
3         dish_3
4         dish_4

DISH_HAS_DISHES

meal_id   dish_id
1         2
1         3
1         4

这里的meal_id和dish_id都是来自DISH表的ID。现在我想要一个这样的格式:

meal_id     dish_ids     dish_names
1           2,3,4        dish_2, dish_3, dish_4

这是逗号分隔的菜肴ID和每餐的名称。怎么做?

1 个答案:

答案 0 :(得分:70)

使用GROUP_CONCAT FUNCTION

http://dev.mysql.com/tech-resources/articles/4.1/grab-bag.html

 SELEct m.meal_Id, 
        GROUP_CONCAT(dish_id) dish_ids, 
        GROUP_CONCAT(dish_name) dish_names
 FROM DISH_HAS_DISHES m JOIN DISH d ON (m.dish_id = d.dish_id)
 GROUP BY meal_Id