CONCAT_WS
使用函數CONCAT_WS()。
使用語法為:
CONCAT_WS(separator,str1,str2,…)
CONCAT_WS() 代表 CONCAT With Separator ,是CONCAT()的特殊形式。
第一個參數是其它參數的分隔符。分隔符的位置放在要連接的兩個字符串之間。
分隔符可以是一個字符串,也可以是其它參數。
如果分隔符為 NULL,則結果為 NULL。函數會忽略任何分隔符參數后的 NULL 值。但是CONCAT_WS()不會忽略任何空字符串。 (然而會忽略所有的 NULL)。
mysql> select concat_ws(',','x','y','z');
+----------------------------+
| concat_ws(',','x','y','z') |
+----------------------------+
| x,y,z |
+----------------------------+
1 row in set (0.00 sec)
CONCAT
CONCAT()函數用于將多個字符串連接成一個字符串。
mysql> select concat(',','x','y','z');
+-------------------------+
| concat(',','x','y','z') |
+-------------------------+
| ,xyz |
+-------------------------+
1 row in set (0.00 sec)
GROUP_CONCAT
如果我們想把下面的查詢列表拼接成逗號(,) 分隔的字符串,怎么搞呢?
mysql> select a.id from article a limit 10;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
+----+
10 rows in set (0.00 sec)
答案:使用GROUP_CONCAT
mysql> select group_concat(a.id) from article a where a.id in
(select t.id from (select id from article limit 10) t );
+----------------------+
| group_concat(a.id) |
+----------------------+
| 1,2,3,4,5,6,7,8,9,10 |
+----------------------+
1 row in set (0.00 sec)
特別指出的是這里in后面的select子句的寫法:
(select t.id from (select id from article limit 10) t )
這里要注意的是,我們不能直接這么寫
mysql> select group_concat(a.id) from article a where a.id in (select a.id from article a limit 10);
ERROR 1235 (42000): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
這也是mysql的子查詢語法用起來不是那么“理所當然”的地方。