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)
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/653220/viewspace-1815322/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/653220/viewspace-1815322/