MySQL GROUP_CONCAT()的使用
Posted 花海漂
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL GROUP_CONCAT()的使用相关的知识,希望对你有一定的参考价值。
1 . MySQL CONCAT(str1,str2, ...)
--返回连接的字符串
mysql> SELECT CONCAT(\'My\', \'S\', \'QL\'); -> \'MySQL\' mysql> SELECT CONCAT(\'My\', NULL, \'QL\'); --若有一个为null,结果为null -> NULL mysql> SELECT CONCAT(14.3); -> \'14.3\'
mysql> SELECT \'My\' \'S\' \'QL\'; --相邻字符会相连接
-> \'MySQL\'
2 . MySQL CONCAT_WS(separater,str1,str2, ...)
concat_wr()是用分隔符连接的特殊的concat(),第一个参数是分隔符,将其余的参数分隔。
-
mysql> SELECT CONCAT_WS(\'--\',\'First name\',\'Second name\',\'Last Name\'); -> \'First name--Second name--Last Name\'
mysql> SELECT CONCAT_WS(\',\',\'First name\',NULL,\'Last Name\'); --连接的遇到null,直接忽略 -> \'First name,Last Name\'mysql> SELECT CONCAT_WS(NULL, \'First name\',NULL,\'Last Name\'); --分隔符为null,结果为null
-> NULLCONCAT_WS()
does not skip empty strings. However, it does skip anyNULL
values after the separator argument.
MySQL GROUP_CONCAT()
1. MySQL GROUP_CONCAT()
mysql> SELECT pub_id,GROUP_CONCAT(cate_id) -> FROM book_mast -> GROUP BY pub_id;
返回结果:(默认逗号分隔)
+--------+-----------------------+
| pub_id | GROUP_CONCAT(cate_id) |
+--------+-----------------------+
| P001 | CA002,CA004 |
| P002 | CA003,CA003 |
| P003 | CA001,CA003 |
| P004 | CA005,CA002 |
| P005 | CA001,CA004 |
| P006 | CA005,CA001 |
| P007 | CA005,CA002 |
| P008 | CA005,CA004 |
+--------+-----------------------+
2.MySQL GROUP_CONCAT() with order by and distinct
语句:(DISTINCT:消重,看结果的第四行CA003,只有一个。ASC:升序)
mysql> SELECT pub_id,GROUP_CONCAT(DISTINCT cate_id) -> FROM book_mast -> GROUP BY pub_id -> ORDER BY GROUP_CONCAT(DISTINCT cate_id) ASC;
返回结果:
+--------+--------------------------------+
| pub_id | GROUP_CONCAT(DISTINCT cate_id) |
+--------+--------------------------------+
| P003 | CA001,CA003 |
| P005 | CA001,CA004 |
| P001 | CA002,CA004 |
| P002 | CA003 |
| P006 | CA005,CA001 |
| P004 | CA005,CA002 |
| P007 | CA005,CA002 |
| P008 | CA005,CA004 |
+--------+--------------------------------
3. MySQL GROUP_CONCAT() with separator
语句: mysql> SELECT pub_id,GROUP_CONCAT(DISTINCT cate_id -> ORDER BY cate_id ASC SEPARATOR \' \') --去除逗号 -> FROM book_mast -> GROUP BY pub_id ;
+--------+----------------
返回结果:
+--------+--------------------------------------------------------------------+
| pub_id | GROUP_CONCAT(DISTINCT cate_id ORDER BY cate_id ASC SEPARATOR \' \') |
+--------+--------------------------------------------------------------------+
| P001 | CA002 CA004 |
| P002 | CA003 |
| P003 | CA001 CA003 |
| P004 | CA002 CA005 |
| P005 | CA001 CA004 |
| P006 | CA001 CA005 |
| P007 | CA002 CA005 |
| P008 | CA004 CA005 |
+--------+--------------------------------------------------------------------+
参考文章:http://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php#
https://dev.mysql.com/doc/refman/5.7/en/string-functions.html
以上是关于MySQL GROUP_CONCAT()的使用的主要内容,如果未能解决你的问题,请参考以下文章
使用 count 和 group_concat 编写 SQL 代码