我有两个桌子。
表:学生
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')
但是它显示了两个学生,因为两个学生都对“数学”感兴趣 结果应该只有1名叫“约翰”的学生
答案 0 :(得分:1)
如果按学生分组,则只能选择具有这两个兴趣的人
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