oracle数据库中in和exists的详细执行过程

发布网友

我来回答

4个回答

热心网友

in和exist的主要区别体现在对sql执行计划的影响上。
传统上认为,如果子查询的条件更具选择性(selective),就用in;而如果父查询(外层查询)的条件更具选择性(selective),就用exist。
具体的内容可以参考以下oracle原厂的手册,不好意思,oracle的原厂手册都是英文版的。

对于你举的那个例子,用in和用or是一样的,因为它们的执行计划肯定是一样的。

另外需要特别注意的是,in和exist的区别只在10.2.0.3及以前的版本中存在;而10.2.0.4及以后的版本中,in和exist的效果是完全一样的,手册中也删除了有关二者区别的说明。

以下是对手册的引用:
In certain circumstances, it is better to use IN rather than EXISTS. In general, if the selective predicate is in the subquery, then use IN. If the selective predicate is in the parent query, then use EXISTS.

Sometimes, Oracle can rewrite a subquery when used with an IN clause to take advantage of selectivity specified in the subquery. This is most beneficial when the most selective filter appears in the subquery and there are indexes on the join columns. Conversely, using EXISTS is beneficial when the most selective filter is in the parent query. This allows the selective predicates in the parent query to be applied before filtering the rows against the EXISTS criteria.

补充:
看sql语句看执行计划就可以了,没必要比较某次的时间长短,因为语句执行时间长短跟很多其他因素有关,比如数据是否在buffer cache中(第二次执行一般会比第一次快不少)、数据库负载不同等。对于常量,in的效果完全等同于or,这是毫无疑问的。

热心网友

IN 其实与等于相似,比如in(1,2) 就是 = 1 or = 2的一种简单写法,所以一般在元素少的时候使用IN,如果多的话就用exists

exists的用法跟in不一样,一般都需要和子表进行关联,而且关联时,需要用索引,这样就可以加快速度。

热心网友

exists是遇到符合条件的记录就返回

in要等全部记录都查询出来之后才返回。

热心网友

  Exists用于只能用于子查询,可以替代in,若匹配到结果,则退出内部查询,并将条件标志为true,传回全部结果资料,in不管匹配到匹配不到都全部匹配完毕,使用exists可以将子查询结果定为常量,不影响查询效果
  In和exists对比:
  若子查询结果集比较小,优先使用in,若外层查询比子查询小,优先使用exists。因为若用in,则oracle会优先查询子查询,然后匹配外层查询,若使用exists,则oracle会优先查询外层表,然后再与内层表匹配。最优化匹配原则,拿最小记录匹配大记录。

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com