数据库not exists 嵌套查询

查询选修了全部课程的学生姓名

SQL语句:

select Sname ---------称它为第一层查询
from student 
where not exists(
select * ------------------称它为第二层查询
from course
where  not exists(
select *  -----------------称它为第三层查询
from sc
where Sno = student.Sno AND Cno = course.Cno)); 


总体理解:

最内部的 select * from sc where cno = course.cno and sno=student.sno是查询出所有已经选择过课程的学生及相应课程,

select * from course where   not exists 则是所有没有被选择的课程,

在这个基础上的 select sname from student where  not exists 则是选取所有没有未选择课程的学生,即选择了所有课程的学员名称。


具体查询过程(猜测):

第一层查询from student(从student表中取出一个元祖)---->where not exists(判断where子句)---->

第二层查询from course(从courset表中取出一个元祖)---->where not exists(判断where子句)---->

第三层查询用from student中取出的一个元组和from course 中取出的一个元组在sc表中查询,满足Sno = student.Sno AND Cno = course.Cno的,第二层查询的where子句返回false,不满足的返回true。从第二层查询中from course(从courset表中取出第二个元祖)---->where not exists(判断where子句),返回,·········直到course表中元组被取完。如果全部都是false,则student表中的Sname被放入结果集,否则不放入。

循环,取student表的第二个元组··············

直到student表中的元组取完,结束。



参考资料:http://wenku.baidu.com/view/1206bed97f1922791688e81b.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值