SELECT ID 在 GROUP_CONCAT

SELECT WHERE id IN GROUP_CONCAT

如何将 WHEREHAVING 子句与 GROUP_CONCAT 结合使用,以便 returned 数据将包含 GROUP_CONCAT 包含 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

会return

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 产品上尝试了 HAVINGWHERE 子句的各种组合。

您应该在 HAVING 子句中使用 FIND_IN_SET。

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 1
GROUP BY p.id,p.title
HAVING FIND_IN_SET('2', aus) > 0 

我很想使用作者的自连接 table,第二个连接检查 author_id of 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