我使用GROUP_CONCAT来连接共享相同cate_idpub_id

SELECT pub_id,GROUP_CONCAT(cate_id)
FROM book_mast
GROUP BY pub_id;


结果是预期的:

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           |
+--------+-----------------------+
6 rows in set (0.02 sec)


但是,如何在相同的SQL查询中进一步过滤出结果,例如我只想输出值为CA005,CA002的行?

最佳答案

您可以在以下位置添加过滤器

SELECT pub_id,GROUP_CONCAT(CATE_ID)
FROM book_mast
WHERE CATE_ID IN  ('CA005','CA001')
GROUP BY pub_id
having count(distinct CATE_ID)  = 2

这样,您还可以过滤订单值

09-17 02:54