oracle--exists与in的效率探讨 ( 转存)

oracle--exists与in的效率探讨 ( 转存)

2017年02月05日 22:50:48 Tate-Ling 阅读数:1354 标签: ORACLEEXISTSIN更多

个人分类: Oracle

转载自:http://blog.itpub.net/223555/viewspace-717946/

Oracle中exists与in的效率探讨

 
  1. select × from 数据表 t where t.x in (...)

  2. 括号内可以是符合t.x字段类型的值集合,如('1','2','3'),但如果t.x是number类型的时候,似乎这样的写法会出问题;也可以是通过 另外的select语句查询出来的值集合,如(select y from 数据表2 where ...)。

 
  1. select * from 数据表 t where [...] and exist (...)

  2. 方括号内为其它的查询条件,可以没有。exist后面的括号内可以是任意的条件,这个条件可以与外面的查询没有任何关系,也可以与外面的条件结合。如: (select * from 数据表2 where 1=1) 或 (select * from 数据表2 where y=t.x)

例子:

 
  1. in的SQL语句

  2. SELECT id, category_id, htmlfile, title, convert(varchar(20),begintime,112) as pubtime

  3. FROM tab_oa_pub WHERE is_check=1 and

  4. category_id in (select id from tab_oa_pub_cate where no='1')

  5. order by begintime desc

 
  1. exists的SQL语句

  2. SELECT id, category_id, htmlfile, title, convert(varchar(20),begintime,112) as pubtime

  3. FROM tab_oa_pub WHERE is_check=1 and

  4. exists (select id from tab_oa_pub_cate where tab_oa_pub.category_id=convert(int,no) and no='1')

  5. order by begintime desc

效率比较:

 
  1. select * from t1 where x in ( select y from t2 )

  2. -- 事实上可以理解为:

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

         如果你有一定的SQL优化经验,从这句很自然的可以想到t2绝对不能是个大表,因为需要对t2进行全表的“唯一排序”,如果t2很大这个排序的性能是不可 忍受的。但是t1可以很大,为什么呢?最通俗的理解就是因为t1.x=t2.y可以走索引。但这并不是一个很好的解释。试想,如果t1.x和t2.y都有 索引,我们知道索引是种有序的结构,因此t1和t2之间最佳的方案是走merge join。另外,如果t2.y上有索引,对t2的排序性能也有很大提高。

 
  1. select * from t1 where exists ( select null from t2 where y = x )

  2. -- 可以理解为:

  3. for x in ( select * from t1 )

  4. loop

  5. if ( exists ( select null from t2 where y = x.x )

  6. then

  7. OUTPUT THE RECORD!

  8. end if

  9. end loop

        这个更容易理解,t1永远是个表扫描!因此t1绝对不能是个大表,而t2可以很大,因为y=x.x可以走t2.y的索引。
        综合以上对IN/EXISTS的讨论,我们可以得出一个基本通用的结论:IN适合于外表大而内表小的情况;EXISTS适合于外表小而内表大的情况。

猜你喜欢

转载自blog.csdn.net/evilcry2012/article/details/83753576
今日推荐