在一个MySQL数据库中,我们有三个表:链接在前两个表之间的“ Answers”,“ Items”和“ AnswerItems”。
答案表
答案ID
(和其他列)
===================
项目表
物品ID
(和其他列)
==================
AnswerItems表
答案ID
物品ID
===============
现在,我们要获得包含某些项目(不多或少)的答案
我们尝试了此操作(假设我们正在搜索包含ID为FirstItemID和SecondItemID的项的答案)
select AnswerID
from AnswerItems
where ItemID in (FirstItemID,SecondItemID)
group by AnswerID
having COUNT(distinct ItemID) = 2
此查询还返回包含其他项目的答案,而上面的两个项目均已选中
SQL提琴:http://sqlfiddle.com/#!2/d9124/3
最佳答案
要查找AnswerID仅具有ItemID 1和2:
SELECT *
FROM AnswerItems t1 INNER JOIN (
SELECT AnswerID
FROM AnswerItems
WHERE ItemID in (1, 2)
GROUP BY AnswerID
HAVING COUNT(DISTINCT ItemID) = 2
) t2 ON t1.AnswerID = t2.AnswerID
GROUP BY t1.AnswerID
HAVING COUNT(*) = 2;