2024年4月21日发(作者:)

SQL 里的 EXISTS与in、not exists与not in

2011-01-07 10:01:25| 分类: sql | 标签: |字号大中小 订阅

系统要求进行SQL优化,对效率比较低的SQL进行优化,使其运行效率更高,其中

要求对SQL中的部分in/not in修改为exists/not exists

修改方法如下:

in的SQL语句

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

pubtime

FROM tab_oa_pub WHERE is_check=1 and

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

order by begintime desc

修改为exists的SQL语句

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

pubtime

FROM tab_oa_pub WHERE is_check=1 and

exists (select id from tab_oa_pub_cate where

tab_oa_ry_id=convert(int,no) and no='1')

order by begintime desc

分析一下exists真的就比in的效率高吗?

我们先讨论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;

——如果你有一定的SQL优化经验,从这句很自然的可以想到t2绝对不能是个大表,

因为需要对t2进行全表的“唯一排序”,如果t2很大这个排序的性能是不可忍受的。但

是t1可以很大,为什么呢?最通俗的理解就是因为t1.x=t2.y可以走索引。但这并不是一

个很好的解释。试想,如果t1.x和t2.y都有索引,我们知道索引是种有序的结构,因此t1

和t2之间最佳的方案是走merge join。另外,如果t2.y上有索引,对t2的排序性能也有

很大提高。