MySql將記錄中的某個字段進行合併

一 將單條記錄中的某個字段合併: concat()
假如對於user表,以下:ide

id class name age
1 1001 zh 18
2 1001 en 19
3 1002 cs 18
4 1002 jp 19

若是想將name 和age 做爲一個字段顯示, 有:code

select id, class, concat(name, ": ", age) as name_age from user;

結果:it

id class name_age
1 1001 zh:18
2 1001 en:19
3 1002 cs: 18
4 1002 jp: 19

二 將多條記錄中的某些字段合併:group_coacat()
依然對上面user表, 若根據年級分組, 並將name和age所有合併在一列中顯示, 有:table

select class, group_concat(name, ":", age) as name_age from user group by class;

結果爲:class

class name_age
1001 zh:18,en:19
1002 cs:18,jp:19

使用group_coacat() 方法默認是以「,」進行分割, 若是但願以其餘字符進行分割可以使用「separator」, 如:select

select class, group_concat(name, ":", age separator ";") as name_age from user group by class;

結果爲:方法

class name_age
1001 zh:18;en:19
1002 cs:18;jp:19
相關文章
相關標籤/搜索