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 6 rows 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 in set (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)