SQL 中的两个条件必须为真
Two condition must be true in SQL
我有两个table。
- 学生
- 学生兴趣
Table:学生
Id | Student Name
------------------
1 | John
2 | Alice
Table:学生兴趣
Id | SId | Interest
------------------
1 | 1 | Mathematics
2 | 1 | Science
1 | 2 | Environment
2 | 2 | English
2 | 2 | Mathematics
这两个table与“student Interest”中的外键相连Table
现在我想要对“数学”和“科学”都感兴趣的学生姓名
我试过了
Select s.Name from Student s
Inner Join StudentInterest si
ON
s.Id = si.SId
Where si.Interest IN ('Mathematics' , 'Science')
但它显示了两个学生,因为两个学生都对 'Mathematics' 感兴趣
结果应该只有 1 个名为“John”的学生
如果你按学生分组,你可以select只有那些像这样有两种兴趣的人
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
我有两个table。
- 学生
- 学生兴趣
Table:学生
Id | Student Name
------------------
1 | John
2 | Alice
Table:学生兴趣
Id | SId | Interest
------------------
1 | 1 | Mathematics
2 | 1 | Science
1 | 2 | Environment
2 | 2 | English
2 | 2 | Mathematics
这两个table与“student Interest”中的外键相连Table
现在我想要对“数学”和“科学”都感兴趣的学生姓名
我试过了
Select s.Name from Student s
Inner Join StudentInterest si
ON
s.Id = si.SId
Where si.Interest IN ('Mathematics' , 'Science')
但它显示了两个学生,因为两个学生都对 'Mathematics' 感兴趣 结果应该只有 1 个名为“John”的学生
如果你按学生分组,你可以select只有那些像这样有两种兴趣的人
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