我们来看两个例子,说明exists 和 in 的用法以及效率
1)select dname from dept t where exists( select null from emp e where e.deptno=t.deptno);
t的数据量小而e表的数据量非常大时,1)的查询效率高
2)select t.dname from dept t where t.deptno in (select e.deptno from emp e);
t的数据量非常大,而e的数据量小时2)的查询效率高
exists 的用法:
“select null from emp e where e.deptno=t.deptno”相当于一个关联查询,相当于
select null from emp e,dept t where e.deptno=t.deptno;
但是,如果你执行1)句括号里的语句会报错,这也是exists使用需要注意的地方
“exists(XXX)”就表示括号里的语句能不能查出记录,它要查的记录是否存在。
因此“select null” 这里的"null" 其实是无关紧要的。换成“1,*”都没有问题,它只在乎括号里的数据能不能查找出来,是否
存在这样的记录,如果存在,1)句的where条件成立。
in 的用法:
“2)select t.dname from dept t where t.deptno in (select e.deptno from emp e);”
这里的“in”后面括号里的语句搜索出来的字段的内容一定要相对应,一般来说,e和t这两个表的deptno字段表达的意义应该是一样的,否则这样查没什么意义
通过使用EXISTS,Oracle会首先检查主查询,然后运行子查询直到它找到第一个匹配项,这就节省了时间。Oracle在执行IN子查询时,首先执行子查询,并将获得的结果列表存放在一个加了索引的临时表中。在执行子查询之前,系统先将主查询挂起,待子查询执行完毕,存放在临时表中以后再执行主查询。这也就是使用EXISTS比使用IN通常查询速度快的原因