使用 Mysql 内置函数 group_concat() 链接查询的字段值

在使用 Mysql 数据库查询数据时,有时需要将查询的同一字段的值拼接起来,减少代码的处理,group_concat() 函数就可以满足我们的需要。

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          |
+----+----------------+

例如,上面的数据表有 category_title 字段,我们在查询时,需要将该字段使用逗号拼接查询,这时需要使用 group_concat( 需要拼接的字段 ) 函数。

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)

该函数默认使用逗号将字符进行拼接,我们也可以传递参数使用指定的字符来拼接, 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,如果字符太长会被截掉,想要完整数据可以在 Mysql 配置文件内增加 group_concat_max_len = '自己需要的长度即可'。

文章同步发布在我的个人博客中,传送门Hesunfly Blog

你可能感兴趣的:(使用 Mysql 内置函数 group_concat() 链接查询的字段值)