SQL-exists
exists语句返回一个bool类型的值,此结构在作为参数的子查询非空
时返回true值。反之not exists空
时返回true值`。
下面举一个简单的例子:
找到2009年秋季学期和2010年春季学期开课的课程号,语句如下:
select course_id
from section as S
where semester = 'Fall' and year = 2009 and exists (
select *
from section as T
where semester = 'Spring' and year = 2010 and S.course_id = T.course_id);
注意
exists ( select *)结构,就是exists后面接的是select *的意思,还有两个重命名操作都很重要。好了,下面我们进入主题。
exists-exists结构
例子:Find the names of all students who have chosen the courses including one course which the NO.1 student has chosen at lease.
翻译:找出选了包含NO.1学生选的课程的所有学生的姓名。
注:NO.1时学号不是排名,这里是包含而不是全部。
select sname
from s
where exists (
select *
from sc as sx --选出NO.1选的课程
where sx.sno=“NO.1” and exists (
select *
from sc as sy
where sy.sno=s.sno and sx.cno=sy.cno));--返回查找学生号,并且有课程和NO.1学生的一致
exists-not exists结构
例子:找出选了不全包含NO.1学生选的课程的所有学生的姓名。
注:这里是包含一节课或者一节课也不包含的学生返回true值,如果全包含的话返回的是false值。
select sname
from s
where exists (
select *
from sc as sx --选出NO.1选的课程
where sx.sno=“NO.1” and not exists (
select *
from sc as sy
where sy.sno=s.sno and sx.cno=sy.cno));--没有一门课和NO.1选的课程一样。
not exists-exists结构
例子:找出选了不包含NO.1学生选的课程的所有学生的姓名。
注:这里必须一节课也不包含NO.1学生选的课才返回true值,否则false。
select sname
from s
where not exists (
select *
from sc as sx --选出NO.1选的课程
where sx.sno=“NO.1” and exists (
select *
from sc as sy
where sy.sno=s.sno and sx.cno=sy.cno));
not exists-not exists结构
例子:找出选了和NO.1学生选的课程的一样的所有学生的姓名。
select sname
from s
where not exists (
select *
from sc as sx --选出NO.1选的课程
where sx.sno=“NO.1” and not exists (
select *
from sc as sy
where sy.sno=s.sno and sx.cno=sy.cno));
我觉得最后一个是最好理解的了,毕竟双重否定表肯定我们学了这么多年。
这里我再加上一些自己的理解,exists-exists结构返回的是包含就可以,但必须要包含,不一定是全部。exists-not exists返回的也有包含的值,但肯定也有不包含的值,他和exists-exists的区别就是他们之间的交集是除了全部包含的值,有点绕,我用几个等式帮助大家理解以下:
exists-exists = 至少包含(有全部包含);
exists-not exists = 包含(但不能全部包含) + 不包含;
not exists-exists = 不包含;
not exists-not exists = 全部包含;