mysql 將多個查詢結果合併成一行
阿新 • • 發佈:2021-06-18
1 mysql中的多行查詢結果合併成一個 2 3 SELECT GROUP_CONCAT(md.data1) FROM DATA md,contacts cc WHERE md.conskey=cc.id AND md.mimetype_id= 5 AND md.user_id=17: 4 5 利用函式:group_concat(),實現一個ID對應多個名稱時,原本為多行資料,把名稱合併成一行,如|1 | 10,20,20| 6 7 8 9 本文通過例項介紹了MySQL中的group_concat函式的使用方法,比如select group_concat(name) 。10 MySQL中group_concat函式 11 完整的語法如下: 12 group_concat([DISTINCT] 要連線的欄位 [Order BY ASC/DESC 排序欄位] [Separator '分隔符']) 13 14 基本查詢 15 mysql> select * from aa; 16 +------+------+ 17 | id| name | 18 +------+------+ 19 |1 | 10| 20 |1 | 20| 21 |1 | 20| 22 |2 | 20| 23 |3 | 200 | 24 |3 | 500 | 25 +------+------+ 26 6rows in set (0.00 sec) 27 28 以id分組,把name欄位的值列印在一行,逗號分隔(預設) 29 mysql> select id,group_concat(name) from aa group by id; 30 +------+--------------------+ 31 | id| group_concat(name) | 32 +------+--------------------+ 33 |1 | 10,20,20| 34 |2 | 20 | 35 |3 | 200,500| 36 +------+--------------------+ 37 3 rows inset (0.00 sec) 38 39 以id分組,把name欄位的值列印在一行,分號分隔 40 mysql> select id,group_concat(name separator ';') from aa group by id; 41 +------+----------------------------------+ 42 | id| group_concat(name separator ';') | 43 +------+----------------------------------+ 44 |1 | 10;20;20 | 45 |2 | 20| 46 |3 | 200;500 | 47 +------+----------------------------------+ 48 3 rows in set (0.00 sec) 49 50 以id分組,把去冗餘的name欄位的值列印在一行, 51 逗號分隔 52 53 mysql> select id,group_concat(distinct name) from aa group by id; 54 +------+-----------------------------+ 55 | id| group_concat(distinct name) | 56 +------+-----------------------------+ 57 |1 | 10,20| 58 |2 | 20 | 59 |3 | 200,500 | 60 +------+-----------------------------+ 61 3 rows in set (0.00 sec) 62 63 以id分組,把name欄位的值列印在一行,逗號分隔,以name排倒序 64 mysql> select id,group_concat(name order by name desc) from aa group by id; 65 +------+---------------------------------------+ 66 | id| group_concat(name order by name desc) | 67 +------+---------------------------------------+ 68 |1 | 20,20,10 | 69 |2 | 20| 70 |3 | 500,200| 71 +------+---------------------------------------+ 72 3 rows in set (0.00 sec)