mysql groupby 拼接_mysql分组并多行拼接--group_concat和groupby的使用

本文介绍了如何在MySQL中使用GROUP_CONCAT函数结合GROUP BY进行数据的分组拼接。通过实例展示了默认逗号连接、自定义连接符、排序连接以及处理低版本MySQL连接数字返回BLOB的方法,帮助理解如何有效聚合和组合多行数据。
摘要由CSDN通过智能技术生成

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

– 创建表结构

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值