ITeye博客

Oracle中in与exists使用上的区别

wanglei8 · 2009-05-27 23:07 · oracle · 数据库 · Markdown

in与exists处理起来是非常不同的。

1.这里使用in方式关联两个表,称为第一个查询。


select * from t1 where x in(select y from t2);

这条sql语句处理起来就像如下:


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

这个子查询被评估,去重复(distincted), 被使用索引(indexed)(或者 hashed 或者 sorted),然后与原始表(t1表)连接

2.这里使用exists方式关联两个表,称为第二个查询。


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

这条sql语句被处理起来更像:


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表产生一个全表扫描(full scan),然而第一个查询能够使用T1表的x列上的索引。 所以,大家有疑问了,在什么时候,在哪里,使用exists适合,或者不适合呢?

好的,下面来看看这个子查询的结果 如果

(select y from t2)

这个表很大,需要花费很长的时间。但是t1表相对小,

(select null from t2 where y = x.x)

这个查询的执行速度非常快(之所以快,得益于t2表y列上的索引),那么exists将会更快。这里,首先全表扫描t1表,对t2做索引查询能够比全表扫描t2表,再构建distinct子查询花更少的时间。

如果

(select y from t2)

子查询的结果小,那么in更合适。

如果子查询和外表都很大(exists和in查询时间差不多),那么就依赖于索引和其他因素了。

声明:JavaEye文章版权属于作者,受法律保护。没有作者书面许可不得转载。

评论(2)

  1. #2 楼 · wanglei8 · 2009-07-17 10:54

    cooldh writes:

    懂了一些。

    这个查询的执行速度非常快(之所以快,得益于t2表y列上的索引),那么exists将会更快。这里,首先全表扫描t1表,对t2做索引查询能够比全表扫描t2表,再构建distinct子查询花更少的时间。

    这里没懂,t1表在哪啊?没看到。

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

    t1表在这里

  2. #1 楼 · cooldh · 2009-06-23 11:34

    懂了一些。

    这个查询的执行速度非常快(之所以快,得益于t2表y列上的索引),那么exists将会更快。这里,首先全表扫描t1表,对t2做索引查询能够比全表扫描t2表,再构建distinct子查询花更少的时间。

    这里没懂,t1表在哪啊?没看到。

评论功能维护中,当前仅展示历史评论。