SQL语言复杂查询-(NOT) Exists
语法:[not] Exists(子查询)
语义:子查询有无元组存在
例:检索选修了赵三老师主讲课程的所有同学姓名。
select DISTINCT Sname From student where exists (select * From SC,Course,Teacher where SC.C#=Course.C# and SC.S#=student.S# and course.T#= Teacher.T# and Tname='赵三');
上面可以直接写为:
select DISTINCT Sname From student, SC,Course,Teacher where SC.C#=Course.C# and SC.S#=student.S# and course.T#= Teacher.T# and Tname='赵三');
上面说明,不加not的Exists语句完全可以不使用的。然而not Exists却可以实现很多功能
例:检索学过001号老师主讲的所有课程所有同学的姓名
select sname From student where not Exists --不存在 (select * From Course --有一门001老师主讲的课程 where Course.T#='001' and not Exists --没学过 (select * From SC where S#=student.S# and C#=Course.C#)); --语义:不存在有一门001号老师讲授的课程·没学过
例:列出学过李明老师任何一门课程的所有同学姓名
select Sname From student where not Exists --不存在 ( select * From Course,Teacher SC --学过一门李明老师的课程 where Tname='李明' and Course.T#=Teachesr.T# and Course.C#=SC.C# and S#=student.S#; --语义:不存在学过一门李明老师的课程