数据库
首页 > 数据库> > mysql-在GROUP_CONCAT中选择WHERE ID

mysql-在GROUP_CONCAT中选择WHERE ID

作者:互联网

如何将WHERE或HAVING子句与GROUP_CONCAT结合使用,以使返回的数据包括GROUP_CONCAT中包含ID的项目的任意组合,而不仅仅是ID的单个匹配项.

SELECT p.id,
p.title,
GROUP_CONCAT(a.author_id) as 'aus'
FROM publications p INNER JOIN authors a
    ON p.publication_id = a.publication_id
WHERE a.author_id = 2
GROUP BY p.id,p.title

会回来

id    title     aus
1     A         1,2,3
2     B         1,2
3     C         2
4     D         2
5     E         2,3

而不是3& 4.

我已经在a.author_id列和GROUP_CONCAT产品上尝试了HAVING和WHERE子句的各种组合.

解决方法:

我很想使用authors表的自连接,第二连接检查author_id为2.

猜测一下您的数据,但是像这样

SELECT p.id,
        p.title,
        GROUP_CONCAT(a.author_id) as 'aus'
FROM publications p 
INNER JOIN authors a ON p.publication_id = a.publication_id
INNER JOIN authors a2 ON p.publication_id = a2.publication_id
WHERE a2.author_id = 2
GROUP BY p.id,
        p.title

标签:group-concat,mysql
来源: https://codeday.me/bug/20191026/1935785.html