对于多对多关系,例如班级和学生,我想选择完全具有给定成员资格的所有Classes
。
Students Classes StudentClass
========= ============ =================
id id student class
-- --- -------- -------
1 1 1 1
2 2 2 1
3 3 1
4 1 2
5 2 2
3 2
4 2
使用示例数据,如果我给查询S1,S2,S3-它应该只返回Class 1,而排除Class 4,因为它包含一个额外的学生。
答案 0 :(得分:3)
以下是使用conditional aggregation
的一种选择:
select class
from studentclass
group by class
having count(case when student in (1,2,3) then 1 end) = 3
and count(*) = 3
答案 1 :(得分:1)
您可以按照以下步骤进行操作:
select class from StudentClass
where class in(
select class from StudentClass where student in(1,2,3)
group by class having count(distinct student)=3
) group by class
having count(distinct student)=3