注册日期: 2004 May 来自: 广州 技术贴数:38 论坛积分:113 论坛排名:13090 论坛徽章:0
Re: 请教关于“IN ”和 “EXISTS”的问题
quote:
最初由 feifei5520 发布 小弟有个问题百思不得其解 我现在有个这样的语句:
select * from goods where code in (select code from goods where code='01010002') 其中“code”为主码,所以执行结果只存在一条记录;
我现在想把他变成 EXISTS的形式 如下:
select * from goods where exists (select *from goods where code='01010002')
可是执行出结果有N条记录,为什么会不一样呢?
我知道肯定是我的方法不对,但是不对在哪里呢? 有请大虾指点一二,不甚感激!
我的理解是exists (select *from goods where code='01010002')对于表goods所有的记录都返回true值,所以会得到n个记录. 问题出在select *from goods where code='01010002' 一直是true.
可以看下面的资料:
在ASKTOM的讲解: Well, the two are processed very very differently.
Select * from T1 where x in ( select y from T2 )
is typically processed as:
select * from t1, ( select distinct y from t2 ) t2 where t1.x = t2.y;
The subquery is evaluated, distinct'ed, indexed (or hashed or sorted) and then joined to the original table -- typically.
As opposed to
select * from t1 where exists ( select null from t2 where y = x )
That is processed more like:
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
It always results in a full scan of T1 whereas the first query can make use of an index on T1(x).
So, when is where exists appropriate and in appropriate?
Lets say the result of the subquery ( select y from T2 )
is "huge" and takes a long time. But the table T1 is relatively small and executing ( select null from t2 where y = x.x ) is very very fast (nice index on t2(y)). Then the exists will be faster as the time to full scan T1 and do the index probe into T2 could be less then the time to simply full scan T2 to build the subquery we need to distinct on.
Lets say the result of the subquery is small -- then IN is typicaly more appropriate.
If both the subquery and the outer table are huge -- either might work as well as the other -- depends on the indexes and other factors.
注册日期: 2005 Mar 来自: 东莞 技术贴数:22 论坛积分:66 论坛排名:19306 论坛徽章:0
楼主去看SQL帮助文件查EXISTS的使用方法就知道了。 EXISTS,如果子查询包含行,则返回 TRUE,只是判断是否存在行记录。 如: select * from goods t1 where exists(select code from goods t2 where t1.code='01010002') 与 select * from goods t1 where code='01010002'一样, 从速度,简洁上看,select * from goods t1 where code='01010002'比较好。
当我们一定要用到exists时候, select * from goods t1 where exists(select code from goods t2 where t1.code='01010002') 比 select * from goods t1 where exists(select 1 from goods t2 where t1.code='01010002') 速度慢。(注:当数据量很大,查询语句非常复杂时候就可以看出来了)