SQL语句之exists-exists/exists-not exists/not exists-exists/not exists-not exists四种搭配的学习

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.1and 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.1and 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.1and 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.1and 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 = 全部包含;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值