mysql合并列值 将一列的多个值合并成一行--group_concat和group by的使用

本文详细介绍了在MySQL中如何使用group_concat和groupby进行数据聚合,包括默认的逗号连接、自定义连接符、排序连接以及解决低版本MySQL连接数字返回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.csdn.net/priestmoon/article/details/7677452

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值