繁体   English   中英

选择具有相关特定记录的记录,但不会记录其他相关记录

[英]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

SQL HERE

您可以像下面这样做:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM