码迷,mamicode.com
首页 > 数据库 > 详细

MySQL GROUP_CONCAT()的使用

时间:2017-05-07 00:09:04      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:font   aggregate   png   resource   tor   技术   使用   mysql   book   


技术分享

 

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#

MySQL GROUP_CONCAT()的使用

标签:font   aggregate   png   resource   tor   技术   使用   mysql   book   

原文地址:http://www.cnblogs.com/xiexiaoxiao/p/6813316.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!