1、表结构
create table tt(id int,v varchar(30));
insert into tt values(1,'a'),(1,'b'),(2,'b'),(2,'c'),(2,'b'),(2,'a'),(3,'a');
mysql> select * from tt;
+------+------+
| id | v |
+------+------+
| 1 | a |
| 1 | b |
| 2 | b |
| 2 | c |
| 2 | b |
| 2 | a |
| 3 | a |
+------+------+
7 rows in set (0.05 sec)
2、问题
一般在合并字符串我们可以用concat,但是这个函数主要实现类似字符串相加的目的,而且是同一行中的字符串的合并。
如果现在要实现把不同行的字符串进行合并,要如何实现呢?
3、解决方法:
完全合并
mysql> select group_concat(v) from tt;
+-----------------+
| group_concat(v) |
+-----------------+
| a,b,b,c,b,a,a |
+-----------------+
1 row in set (0.05 sec)
分组合并
mysql> select id,group_concat(v) from tt group by id;
+------+-----------------+
| id | group_concat(v) |
+------+-----------------+
| 1 | a,b |
| 2 | b,c,b,a |
| 3 | a |
+------+-----------------+
3 rows in set (0.01 sec)
分组、去重合并
mysql> select id,group_concat(distinct v) from tt group by id;
+------+--------------------------+
| id | group_concat(distinct v) |
+------+--------------------------+
| 1 | a,b |
| 2 | b,c,a |
| 3 | a |
+------+--------------------------+
3 rows in set (0.03 sec)
分组、去重、排序合并
mysql> select id,group_concat(distinct v order by v) from tt group by id;
+------+-------------------------------------+
| id | group_concat(distinct v order by v) |
+------+-------------------------------------+
| 1 | a,b |
| 2 | a,b,c |
| 3 | a |
+------+-------------------------------------+
3 rows in set (0.00 sec)
自定义连接符
mysql> select id,group_concat(v separator ';') from tt group by id;
+------+-------------------------------+
| id | group_concat(v separator ';') |
+------+-------------------------------+
| 1 | a;b |
| 2 | b;c;b;a |
| 3 | a |
+------+-------------------------------+
3 rows in set (0.01 sec)
---------------------