注册 登录
编程论坛 SQL Server论坛

请问如何理解exists?

hellenism 发布于 2009-12-23 22:23, 774 次点击
拿《数据库系统概论》的例子说:

sleect Sname
from Student
where not exists(select *
                 from Course
                 where not exists (select *
                                   from sc
                                   where Sno=Student.Sno and
                                         Cno=))

请问:
1.执行过程是什么呢?
2.如何来理解它呢?我总是理解不了.....
3.用其他方法可以吗?
2 回复
#2
msgj2009-12-25 17:01
关系模式:
学生(学号,姓名,系别,年龄)
课程(课程号,课程名,学时)
选读(学号,课程号,成绩)
问题:检索选读全部课程的学生姓名
select 学生.姓名 from 学生
where not exists(
select * from 课程 where not exists(
select * from 选读 where 学号=学生.学号 and 课程号=课程.课程号))

现在我们从后面的子查询向前分解:

1.所有未选过的课程的数据集:
select * from 课程 where not exists(
select * from 选读 where 课程号=课程.课程号)

2.所有没被某位学号为 @学号 的学生选过的课程的记录集(@学号学生的未选课程):
select * from 课程 where not exists(
select * from 选读 where 学号=@学号 and 课程号=课程.课程号)
请注意,多出了学号的筛选即,学号=@学号。

3.遍历每一个主查询的学号,每一个学号都按第二筛选方法筛选出:没有未选课程的学生的学号。(不包括在第查询方法查询出的“有未学课程的学号的记录集”中的记录。)
请注意:用主查询中的 学生.学号 代替了@学号。
select 学生.姓名 from 学生
where not exists(
select * from 课程 where not exists(
select * from 选读 where 学号=学生.学号 and 课程号=课程.课程号))

这已经是整个查询语句,可以看出子查询中用学生.学号替换了第2步中的 @学号,(没忘了吧,第二步求的是没有选修全部课程的某个学生)。
#3
我就是找抽的2009-12-30 21:08
解释的很好啊
1