![](/img/trans.png)
[英]Select rows from a table where row in another table with multiple condition
[英]Select from a table where a condition is fulfilled and another is not
我有3张桌子:
Students
(student_id, name, group, year, specialization)
Scolarships
(scolarship_id, name, description, duration)
Applicants
(student_id, scolarship_id)
我需要选择所有已申请id=2
的奖学金但尚未申请id=4
奖学金的学生
到目前为止,我有这个查询:
select students.name, students.group, students.specialization
from applicants ap
inner join students on students.id = ap.student_id
inner join scolarships on scolarships.scolarship_id = ap.scolarship_id
where ap.scolarship_id = 2;
这将选择所有申请了id = 2的奖学金的学生。
我如何添加他们已申请奖学金2但未申请奖学金4的条件?
尝试这个
select students.name, students.group, students.specialization
from applicants ap
inner join students on students.id = ap.student_id
inner join scolarships on scolarships.scolarship_id = ap.scolarship_id
where ap.scolarship_id = 2 and not exists(select * from applicants as t1
where t1.student_id = students.student_id and t1.scolarship_id = 4)
您可以使用not exists
东西作为
select students.name, students.group, students.specialization
from applicants ap
inner join students on students.id = ap.student_id
inner join scolarships on scolarships.scolarship_id = ap.scolarship_id
where
ap.scolarship_id = 2
and not exists(
select 1 from applicants ap1
where
ap.student_id = ap1.student_id
and ap1.scolarship_id = 4
)
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.