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


– 创建表结构


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

你可能感兴趣的:(MySQL)