The group_concat function in MySQL is well understood

  • 2020-05-13 03:41:21
  • OfStack

This article introduces the use of the group_concat function in MySQL by example, such as select group_concat(name).
group_concat function in MySQL
The full syntax is as follows:
group_concat([DISTINCT] field to join [Order BY ASC/DESC sort field] [Separator 'separator '])
The basic query
mysql > select * from aa;
+------+------+
| id| name |
+------+------+
|1 | 10|
|1 | 20|
|1 | 20|
|2 | 20|
|3 | 200 |
|3 | 500 |
+------+------+
6 rows in set (0.00 sec)
Group by id and print the values of the name field on line 1, separated by commas (default)
mysql > select id,group_concat(name) from aa group by id;
+------+--------------------+
| id| group_concat(name) |
+------+--------------------+
|1 | 10,20,20|
|2 | 20 |
|3 | 200,500|
+------+--------------------+
3 rows in set (0.00 sec)
Group by id and print the values of the name field on line 1, separated by semicolons
mysql > select id,group_concat(name separator ';') from aa group by id;
+------+----------------------------------+
| id| group_concat(name separator ';') |
+------+----------------------------------+
|1 | 10;20;20 |
|2 | 20|
|3 | 200;500 |
+------+----------------------------------+
3 rows in set (0.00 sec)
Group with id, print the value of the unredundant name field in line 1,
A comma
mysql > select id,group_concat(distinct name) from aa group by id;
+------+-----------------------------+
| id| group_concat(distinct name) |
+------+-----------------------------+
|1 | 10,20|
|2 | 20 |
|3 | 200,500 |
+------+-----------------------------+
3 rows in set (0.00 sec)
Group by id and print the values of the name field on line 1, separated by commas, in reverse order by name
mysql > select id,group_concat(name order by name desc) from aa group by id;
+------+---------------------------------------+
| id| group_concat(name order by name desc) |
+------+---------------------------------------+
|1 | 20,20,10 |
|2 | 20|
|3 | 500,200|
+------+---------------------------------------+
3 rows in set (0.00 sec)
Using the group_concat_max_len system variable, you can set the maximum allowed length. The syntax for doing this in the program is as follows, where val is an unsigned integer:
SET [SESSION | GLOBAL] group_concat_max_len = val;
If a maximum length has been set, the result is truncated to that maximum length.
Increase the environment variable group_concat_max_len. The default is 1024. I set the session level environment variable to 2048. Solve the problem

Related articles: