標籤:
本文通過執行個體介紹了MySQL中的group_concat函數的使用方法,比如select group_concat(name) 。MySQL中group_concat函數完整的文法如下:group_concat([DISTINCT] 要串連的欄位 [Order BY ASC/DESC 排序欄位] [Separator ‘分隔字元‘])基本查詢 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)以id分組,把name欄位的值列印在一行,逗號分隔(預設) 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)以id分組,把name欄位的值列印在一行,分號分隔 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)以id分組,把去冗餘的name欄位的值列印在一行, 逗號分隔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)以id分組,把name欄位的值列印在一行,逗號分隔,以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)
有長度限制的,長度設定 請看 group_concat的長度設定連結。
簡單用法:
SET GLOBAL group_concat_max_len=102400;後直接跟包含group_concat 的sql語句即可。(全域 查詢 的設定,只要設定,這個mysql伺服器 下 這兒長度就永久設定成這個值。 )
SET SESSION group_concat_max_len=102400;後直接跟包含group_concat 的sql語句即可。(一次session查詢 的設定,只會在同一個session 下的查詢才會生效 )
MySQL中group_concat函數 --- 很有用的一個用來查詢出所有group by 分組後所有 同組內的 內容