SELECT news.*, COUNT(*) c
FROM news
INNER JOIN tags ON tags.newsid = news.id
WHERE tags.name IN ("test", "test2")
HAVING c = 2
我假设的组合tags.newsid, tags.name
是独一无二的。
这是您在评论中要求的操作方式。
SELECT news.*, COUNT(*) c
FROM news n
INNER JOIN (
SELECT tags.newsid newsid
FROM tags
WHERE tags.name = "test"
UNION ALL
SELECT DISTINCT tags.newsid
FROM tags
WHERE tags.name IN ("test2", "test3")
) t
ON t.newsid = n.id
HAVING c = 2
另一种方法是:
SELECT DISTINCT news.*
FROM news n
JOIN tags t1 ON n.id = t1.newsid
JOIN tags t2 ON n.id = t2.newsid
WHERE t1.name = "test"
AND t2.name IN ("test2", "test3")
后一种方法更容易外推到任意组合。