SQL中必须满足两个条件

时间:2020-06-23 07:12:23

标签: sql relational-division

我有两个桌子。

  1. 学生
  2. 学生兴趣

表:学生

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名叫“约翰”的学生

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
相关问题