SELECT WHERE id IN GROUP_CONCAT

时间:2017-01-17 12:08:38

标签: mysql group-concat

如何将WHEREHAVING子句与GROUP_CONCAT结合使用,以便返回的数据将包含GROUP_CONCAT中包含的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不仅仅是单一匹配,例如

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

将返回

HAVING

而不仅仅是3& 4。

我已经在a.author_id列和WHERE产品上尝试了GROUP_CONCATgetSupportFragmentManager().beginTransaction().remove(fragment). commitAllowingStateLoss(); 条款的各种组合。

2 个答案:

答案 0 :(得分:3)

你应该在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 

答案 1 :(得分:1)

我很想使用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