ORACLE 中IN和EXISTS比较
--先记下来,回头验证下
EXISTS的执行流程
select * from t1 where exists ( select null from t2 where y = x )
可以理解为:
for x in ( select * from t1 )
loop
if ( exists ( select null from t2 where y = x.x )
then
OUTPUT THE RECORD
end if
end loop
对于in 和 exists的性能区别:
如果子查询得出的结果集记录较少,主查询中的表较大且又有索引时应该用in,反之如果外层的主查询记录较少,子查询中的表大,又有索引时使用exists。
其实我们区分in和exists主要是造成了驱动顺序的改变(这是性能变化的关键),如果是exists,那么以外层表为驱动表,先被访问,如果是IN,那么先执行子查询,所以我们会以驱动表的快速返回为目标,那么就会考虑到索引及结果集的关系了
另外IN时不对NULL进行处理
如:
select 1 from dual where null in (0,1,2,null)
为空
从性能上来看
exists是用loop的方式,循环的次数影响大,外表要记录数少,内表就无所谓了
in用的是hash join,所以内表如果小,整个查询的范围都会很小,如果内表很大,外表如果也很大就很慢了,这时候exists才真正的会快过in的方式。
not in和not exists的区别
not in内外表都进行全表扫描,没有用到索引;
not extsts 的子查询能用到表上的索引。
所以推荐用not exists代替not in
不过如果是exists和in就要具体看情况了
create table build_tab
initrans 3
nologging
as
with generator as (
select --+ materialize
rownum id
from all_objects
where rownum <= 3000
)
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28859270/viewspace-765695/
,如需转载,请注明出处,否则将追究法律责任。