Detailed explanation of group_concat function of mysql
group_concat( [DISTINCT] Field to be connected [Order BY sort field ASC/DESC] [Separator 'Separator'])
The following example illustrates:
select * from goods;
+------+-- ----+
| id| price|
+------+------+
|1 | 10|
|1 | 20|
|1 | 20|
|2 | 20|
|3 | 200 |
|3 | 500 |
+------+------+
6 rows in set (0.00 sec)
Group by id, print the value of the price field in the same row, separated by commas (default)
select id , group_concat(price) from goods group by id;
+------+--------------------------------+
| id| group_concat(price) |
+- -----+--------------------------------+
|1 | 10,20,20|
|2 | 20 |
|3 | 200,500|
+------+--------------------------------+
3 rows in set (0.00 sec)
group by id and print the value of the price field on one line , semicolon separated
select id,group_concat(price separator ';') from goods group by id;
+------+--------------------------------- -------------+
| id| group_concat(price separator ';') |
+------+---------------- ------------------+
|1 | 10;20;20 |
|2 | 20|
|3 | 200;500 |
+------+-- --------------------------------+
3 rows in set (0.00 sec)
are grouped by id to remove duplicate redundancy The value of the price field is printed on one line, comma separated
select id,group_concat(distinct price) from goods group by id;
+------+----------------- ------------+
| id| group_concat(distinct price) |
+------+-------------------- ---------+
|1 | 10,20|
|2 | 20 |
|3 | 200,500 |
+------+------------------------- ----+
3 rows in set (0.00 sec)
Group by id, print the value of the price field on one line, separated by commas, and sort in reverse
order by price select id, group_concat(price order by price desc) from goods group by id;
+------+---------------------------------------+
| id | group_concat(price order by price desc) |
+------+-------------------------------- -------+
|1 | 20,20,10 |
|2 | 20|
|3 | 500,200|
+------+--------------- ------------------------+
3 rows in set (0.00 sec)
MySQL common function group_concat
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326271901&siteId=291194637
Recommended
Ranking