group_concat( [DISTINCT] 要連接的字段 [Order BY 排序字段 ASC/DESC] [Separator '分隔符'] )


下面舉例說明:

select * from goods;  

+------+------+
| id| price|
+------+------+
|1 | 10|
|1 | 20|
|1 | 20|
|2 | 20|
|3 | 200 |
|3 | 500 |
+------+------+
6 rows in set (0.00 sec)


以id分組,把price字段的值在同一行打印出來,逗號分隔(默認)

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)


以id分組,把price字段的值在一行打印出來,分號分隔 

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)


以id分組,把去除重復冗余的price字段的值打印在一行,逗號分隔

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)


以id分組,把price字段的值打印在一行,逗號分隔,按照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)

@非原創


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM