oracle中in和exists的区别

IN适合于外表大而内表小的情况;EXISTS适合于外表小而内表大的情况。

性能上的比较

比如Select * from T1 where x in ( select y from T2 )

执行的过程相当于:

select *
  from t1, ( select distinct y from t2 ) t2
 where t1.x = t2.y;

相对的

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

表T1不可避免的要被完全扫描一遍

分别适用在什么情况?

以子查询( select y from T2 )为考虑方向

如果子查询的结果集很大需要消耗很多时间,但是T1比较小执行( select null from t2 where y = x.x )非常快,那么exists就比较适合用在这里。

相对应得子查询的结果集比较小的时候就应该使用in.

原文地址:https://www.cnblogs.com/qinjf/p/8433327.html