数据库not exists 嵌套查询

原创
2016-06-07 15:41:35 1887浏览

查询选修了全部课程的学生姓名 SQL语句: select Sname---------称它为第一层查询 from student where not exists( select *------------------称它为第二层查询 from course where not exists( select *-----------------称它为第三层查询 from sc where Sn

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

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

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。