MySql將記錄中的某個字段進行合並
阿新 • • 發佈:2018-01-09
class group mysq 其他 pre from 默認 lec select 一 將單條記錄中的某個字段合並: concat()
假如對於user表,如下:
依然對上面user表, 若根據年級分組, 並將name和age全部合並在一列中顯示, 有:
假如對於user表,如下:
id | class | name | age |
---|---|---|---|
1 | 1001 | zh | 18 |
2 | 1001 | en | 19 |
3 | 1002 | cs | 18 |
4 | 1002 | jp | 19 |
如果想將name 和age 作為一個字段顯示, 有:
select id, class, concat(name, ": ", age) as name_age from user;
結果:
id | class | name_age |
---|---|---|
1 | 1001 | zh:18 |
2 | 1001 | en:19 |
3 | 1002 | cs: 18 |
4 | 1002 | jp: 19 |
二 將多條記錄中的某些字段合並:group_coacat()
select class, group_concat(name, ":", age) as name_age from user group by class;
結果為:
class | name_age |
---|---|
1001 | zh:18,en:19 |
1002 | cs:18,jp:19 |
使用group_coacat() 方法默認是以“,”進行分割, 如果希望以其他字符進行分割可使用“separator”, 如:
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 |
MySql將記錄中的某個字段進行合並