MySQL将多条数据的单个字段合并成一条数据group_concat函数

本文介绍了 MySQL 中 group_concat 函数的基本用法及其语法结构,包括如何使用 DISTINCT、ORDER BY 和自定义分隔符等功能,并提供了具体的示例查询语句。

在MySQL中有个group_concat函数能够将多条数据的单个字段合并到一条数据中。
完整语法如下:

group_concat([DISTINCT] 要连接的字段 [ORDER BY ASC/DESC 排序字段] [separator ‘分隔符’])

例如:

+—-+——–+——+———-+
| id | name | num | store_id |
+—-+——–+——+———-+
| 1 | sing | 1 | 1 |
| 2 | dance | 2 | 1 |
| 3 | basket | 2 | 2 |
| 4 | apple | 3 | 2 |
+—-+——–+——+———-+
查询语句(DOS复制太麻烦,直接截图了):

select id,group_concat(name) from product group by store_id;

group_concat

select store_id,group_concat(name),sum(num) from product group by store_id;

group_concat,sum

select store_id,group_concat(name order by store_id desc Separator ‘*’),sum(num) from product group by store_id;

group_concat(order by ...Separator)

昨天项目中遇到这种情况,记录一下,嗯。
另外,记得group by ,否则查询出来的所有的记录都变成一条数据了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值