在使用 Mysql 數(shù)據(jù)庫查詢數(shù)據(jù)時,有時需要將查詢的同一字段的值拼接起來,減少代碼的處理,group_concat() 函數(shù)就可以滿足我們的需要。
mysql> select `id`, `category_title` from `categories`;
+----+----------------+
| id | category_title |
+----+----------------+
| 9 | Golang |
| 5 | Http |
| 1 | Javascript |
| 3 | Linux |
| 10 | Mac |
| 6 | Mysql |
| 7 | Nginx |
| 2 | PHP |
| 8 | Redis |
| 4 | Tools |
+----+----------------+
例如,上面的數(shù)據(jù)表有 category_title 字段,我們在查詢時,需要將該字段使用逗號拼接查詢,這時需要使用 group_concat( 需要拼接的字段 ) 函數(shù)。
mysql> select group_concat(`category_title`) as title from `categories`;
+--------------------------------------------------------------+
| title |
+--------------------------------------------------------------+
| Golang,Http,Javascript,Linux,Mac,Mysql,Nginx,PHP,Redis,Tools |
+--------------------------------------------------------------+
1 row in set (0.00 sec)
該函數(shù)默認使用逗號將字符進行拼接,我們也可以傳遞參數(shù)使用指定的字符來拼接, group_concat( 需要拼接的字段 separator '拼接字符' )。
mysql> select group_concat(`category_title` separator '|' ) as title from `categories`;
+--------------------------------------------------------------+
| title |
+--------------------------------------------------------------+
| Golang|Http|Javascript|Linux|Mac|Mysql|Nginx|PHP|Redis|Tools |
+--------------------------------------------------------------+
1 row in set (0.00 sec)
需要注意的是 Mysql 默認長度1024,如果字符太長會被截掉,想要完整數(shù)據(jù)可以在 Mysql 配置文件內(nèi)增加 group_concat_max_len = '自己需要的長度即可'。
文章同步發(fā)布在我的個人博客中,傳送門Hesunfly Blog