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))
检索选修全部课程同学的姓名=该学生
à不存在这样的(课程
à该课程该同学没有选)