Merge a field in a single record: Concat ()
If for the user table, the following:
ID |
class |
name |
| Age
1 |
1001 |
Zh |
18 |
2 |
1001 |
En |
19 |
3 |
1002 |
Cs |
18 |
4 |
1002 |
Jp |
19 |
If you want to display name and age as a field, there are:
select id, class, concat(name, ": ", age) as name_age from user;
Results:
ID |
class |
Name_age |
1 |
1001 |
Zh:18 |
2 |
1001 |
En:19 |
3 |
1002 |
Cs:18 |
4 |
1002 |
Jp:19 |
Two merge some fields from multiple records: Group_coacat ()
Still on the user table above, if grouped by grade, and the name and age are all combined in one column, there are:
select class, group_concat(name, ":", age) as name_age from user group by class;
The result is:
class |
Name_age |
1001 |
Zh:18,en:19 |
1002 |
Cs:18,jp:19 |
Using the Group_coacat () method, by default, is split with "," and if you want to split with other characters you can use "separator", such as:
select class, group_concat(name, ":", age separator ";") as name_age from user group by class;
The result is:
class |
Name_age |
1001 |
Zh:18;en:19 |
1002 |
Cs:18;jp:19 |
MySQL merges a field in the record