SQL程式設計:group 不用合併結果字串 ---> group_concat函式就能行
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)---------------------