mysql分组并多行拼接--group_concat和group by的使用

本文介绍了如何在MySQL中利用GROUP_CONCAT函数结合GROUP BY子句进行数据的分组和多行拼接。通过示例展示了默认逗号连接、自定义连接符、排序连接以及处理数字连接时的BLOB对象转换。同时提供了相关参考链接以供深入学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


– 创建表结构


DROP TABLE IF EXISTS exe;
CREATE TABLE exe (
id int(3) NOT NULL,
type int(3) default NULL,
name varchar(10) default NULL,
other int(3) default NULL,
text int(255) default NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


– 插入测试数据


INSERT INTO exe VALUES (‘1’, ‘1’, ‘分拼’, ‘2’, ‘1’);
INSERT INTO exe VALUES (‘2’, ‘1’, ‘四维’, ‘3’, ‘2’);
INSERT INTO exe VALUES (‘3’, ‘2’, ‘总评’, ‘1’, ‘4’);
INSERT INTO exe VALUES (‘4’, ‘3’, ‘季度’, ‘5’, ‘3’);


– group_concat和group by的使用


– 默认逗号连接
select t.type,group_concat(t.name) “result” from exe t group by t.type;

– separator指定连接符
select t.type,group_concat(t.name separator ‘;’) “result” from exe t group by t.type;

– 排序连接
select t.type,group_concat(t.name order by t.other desc) “result” from exe t group by t.type;

select t.type,group_concat(t.name order by t.other) “result” from exe t group by t.type;

– 低版本mysql连接数字会返回BLOB大对象,需要用cast()转换成char类型
select t.type,group_concat(t.name) “name”,group_concat(t.other) “result” from exe t group by t.type;

select t.type,group_concat(t.name) “name”,group_concat(CAST(t.other AS char)) “result” from exe t group by t.type;

参考文章:
http://blog.163.com/lgh_2002/blog/static/44017526201111144316650/

http://blog.youkuaiyun.com/priestmoon/article/details/7677452

http://www.jb51.net/article/40179.htm

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值