mysql行逗号分隔符,MySQL:多行以逗号分隔单行

I have two tables : DISH and DISH_HAS_DISHES. Dish table has all the dishes and "Dish_has_dishes" table has a one-to-many relationship with "Dish" table. I.e. a dish can have multiple dishes. For example

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

Here meal_id and dish_id both are IDs from DISH table. Now I want a format like this:

meal_id dish_ids dish_names

1 2,3,4 dish_2, dish_3, dish_4

That is comma separated dish id and names for each meal. How to do that?

解决方案

Use GROUP_CONCAT FUNCTION

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值