SQL中的两个条件必须为true
我有两张桌子SQL中的两个条件必须为true,sql,relational-division,Sql,Relational Division,我有两张桌子 学生 学生兴趣 表:学生 Id | Student Name ------------------ 1 | John 2 | Alice 表:学生兴趣 Id | SId | Interest ------------------ 1 | 1 | Mathematics 2 | 1 | Science 1 | 2 | Environment 2 | 2 | English 2 | 2 | Mathematics 这两个表与“学生兴趣”表中的外键相
Id | Student Name
------------------
1 | John
2 | Alice
表:学生兴趣
Id | SId | Interest
------------------
1 | 1 | Mathematics
2 | 1 | Science
1 | 2 | Environment
2 | 2 | English
2 | 2 | Mathematics
这两个表与“学生兴趣”表中的外键相连
现在我想知道对“数学”和“科学”都感兴趣的学生的名字
我试过这个
Select s.Name from Student s
Inner Join StudentInterest si
ON
s.Id = si.SId
Where si.Interest IN ('Mathematics' , 'Science')
但它显示了两个学生,因为两个学生都对“数学”感兴趣
结果应该只有一个名为“John”的学生如果你按学生分组,你只能选择像这样有两种兴趣的学生
Select s.Name
from Student s
Inner Join StudentInterest si ON s.Id = si.SId
Where si.Interest IN ('Mathematics' , 'Science')
group by s.Name
having count(distinct si.Interest) = 2
或
Select s.Name
from Student s
Inner Join StudentInterest si ON s.Id = si.SId
group by s.Name
having sum(case when si.Interest = 'Mathematics' then 1 else 0 end) > 0
and sum(case when si.Interest = 'Science' then 1 else 0 end) > 0