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
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;