标签:合并 name table 显示 mysq 记录 ble group by group
一 将单条记录中的某个字段合并: concat()
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()
依然对上面user表, 若根据年级分组, 并将name和age全部合并在一列中显示, 有:
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 |
标签:合并 name table 显示 mysq 记录 ble group by group
原文地址:http://blog.51cto.com/yinbin99/2059014