NOT EXISTS 相关子查询举例

 NOT EXISTS 作用正好与EXISTS相反,如果用NOT EXISTS实现相关子查询的话,就能收到一些预想不到的效果。举一些例子,三张表

s(sno,sname,sage,ssex)
sc(sno,cno,grade)
c(cno,cname,teacher)
其中:s为学生表,sc为选课表,c为课程表,sno--学号,sname--姓名,sage--年龄,ssex--性别,cno--课程号,grade--成绩,cname--课程名,teacher--教师名。
1、检索至少选修LIU老师所授全部课程的学生姓名;
2、检索选修全部课程同学的姓名;
3、检索全部同学都选修的课程的课程号、课程名;
4、检索选修课程包含LI同学所选修全部课程的同学的姓名;
5、检索选修课程与LI同学所选修课程完全一样的同学的姓名。
用SQL语言实现查询
1、select sname from s where not exists (select * from c where teacher='LIU' and not exists (select * from sc where sc.cno=c.cno and sc.sno=s.sno));
找出这样的学生X,这个学生满足这样的条件,不存在刘老师教的课程他没有选,not exists (select * from sc where sc.cno=c.cno and sc.sno=s.sno)的意思是X同学没选刘老师教的那门课。
2、select sname from s where not exists (select * from c where not exists (select * from sc where sc.cno=c.cno and sc.sno=s.sno));
不存在某课程那个同学没有选
3、select cno,cname from c where not exists (select * from s where not exists (select * from sc where sc.cno=c.cno and sc.sno=s.sno));
那门课程不存在S表中某个同学没有选
4、select sname from s sx where not exists (select * from sc scx,s sy where scx.sno=sy.sno and sy.sname='LI' and not exists (select * from sc scy where scy.cno=scx.cno and scy.sno=sx.sno));
5、select sname from s sx where not exists (select * from sc sca,s sy where sca.sno=sy.sno and sy.sname='LI' and not exists (select * from sc scb where scb.cno=sca.cno and scb.sno=sx.sno)) and not exists (select * from sc scc where scc.sno=sx.sno and not exists (select * from sc scd,s sz where scc.cno=scd.cno and scd.sno=sz.sno and sz.sname='LI'));
 
NOT EXISTS的使用关键要明白NOT EXISTS的意思,它的意思就是不存在,就拿第二个例子来说吧:
select sname from s where not exists (select * from c where not exists (select * from sc where sc.cno=c.cno and sc.sno=s.sno))
检索选修全部课程同学的姓名=该学生 à不存在这样的(课程 à该课程该同学没有选)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值