带有exists谓词的子查询 嵌套查询

Exists,NOT EXISTS:
1.含义:带有exists谓词的子查询不返回任何实际数据,它只产生逻辑真值true或逻辑假值false。

2.查询所有选修了c1号课程的学生姓名:

   select sn from s where exists (select * from sc where sno=s.sno and cno='c1')

注:若内查询结果(select * from sc where sno=s.sno and cno='c1')为空,则外层的where子句返回真值,否则返回假值!

查询过程:步骤一:从外层查询中的s表的第一个元组,根据它,与内层查询相关的属性值(sno值)处理内层查询,若where查询子句返回值为真(及内层查询非空),则取此元组放入结果表;

                 步骤二:  在检查s表中下一个元组;

                 步骤三:重复这一过程,直至s表全部检查完毕为止!

3。查询所有未修c1课程的学生姓名:

   select sn from s where not exists (select * from sc where sno=s.sno and cno='c1')
 

4.查询与“王林”在同一系学习的学生的信息

   select * from s s1 where exists (select * from s s2 where s2.dept=s1.dept and s2.sn='王林')

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

   select sn from s where not exists(select * from c where not exists(select * from sc where sno=s.sno and cno=c.cno))

数据库表s,c,sc截图请到截图地址

posted @ 2012-02-02 21:57  偶不是大叔  阅读(6266)  评论(1编辑  收藏  举报