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:html
利用函數:group_concat(),實現一個ID對應多個名稱時,本來爲多行數據,把名稱合併成一行,如|1 | 10,20,20|mysql
本文經過實例介紹了MySQL中的group_concat函數的使用方法,好比select group_concat(name) 。
MySQL中group_concat函數
完整的語法以下:
group_concat([DISTINCT] 要鏈接的字段 [Order BY ASC/DESC 排序字段] [Separator '分隔符'])sql
基本查詢
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)spa
以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).net
以id分組,把去冗餘的name字段的值打印在一行,
逗號分隔htm
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)blog
以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)排序
http://www.cnblogs.com/bruceleeliya/p/3310137.htmlget