in查询:(left expression)in (select_sub_expression )
exists 查询:(left expression)exists (select_sub_expression )
两种方式的执行过程有些差别。执行EXISTS子查询,数据库系统会首先检查主查询,然后运行子查询 直到它找到第一个匹配项。执行IN子查询,首先执行子查询,并将获得的结果列表存放在在一个加了索引的临时表中。在执行子查询之前,系统先将主查询挂起, 待子查询执行完毕,存放在临时表中以后再执行主查询。还是昨天的例子
有3个表:
s:学生表;
c:课程表;
sc:选课表
--查询一个sid为002的学生没有选的课程,用in查询的语句是:
1):select * from c where c.cid not in (select sc.cid from sc where s.sid='002')
--等价于下面的exsits语句
2):select * from c where not exists (select sc.cid from sc where s.sid='002' and c.cid = sc.cid)
语句1先执行子查询,即先把所有002学生选的课程的ID查出来了,然后执行主查询,看看哪些课程的ID不在子查询的结果集中。
语句2先执行主查询,即先把所有的课程查出来,然后再遍历结果集,看看not exists是不是true。找到满足c.cid <> sc.cid(因为exists前有一个not)的条件时,便输出。
考虑下面的查询:
--选修了所有课程的学生==不存在一门课,该学生没有选
select sname from s where not exists(
select * from c where c.cid not in (select cid from sc where sc.sid = s.sid))
==
select sname from s where not exists(
select * from c where not exsits (select cid from sc where sc.sid = s.sid and c.cid = sc.sid))
没有评论:
发表评论