在MySQL数据库中,我们有三个表:'答案''项目'和' AnswerItems'前两个表之间的链接。
答案表
AnswerID
(和其他专栏)
===================
项目表
的ItemID
(和其他专栏)
==================
AnswerItems表
AnswerID
的ItemID
===============
现在,我们希望获得具有某些项目(不多或少)的答案
我们尝试了这个(假设我们正在搜索包含ID项目的答案:FirstItemID和SecondItemID)
select AnswerID
from AnswerItems
where ItemID in (FirstItemID,SecondItemID)
group by AnswerID
having COUNT(distinct ItemID) = 2
此查询还会返回包含上述所选两个项目的其他项目的答案
答案 0 :(得分:1)
要查找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;
答案 1 :(得分:0)
您可以尝试以下
SELECT * FROM AnswerItems
where ItemID in (1,2)
group by Answerid having count(*) = 2