![](/img/trans.png)
[英]SQL: Select records from one table if another table with related records has no specific value
[英]Select record that has specific records related, but no additional records related
对于多对多关系,例如Classes和Students,我想选择具有完全给定成员资格的所有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,因为它包含一个额外的学生。
这是使用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
您可以像下面这样做:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.