NOT IN虽然比较符合我们的习惯,但是系统去编译的时候,会先转化为exists来执行,以前看到的
一篇文章,文摘我一下子找不到!用in,会先执行子查询(这样如果表的纪录多速度贼慢),然后将符
合条件的纪录列表放到一个临时表,然后再执行主查询!相对exists只管到where子句,我们知道我们
的纪录存储采取B-Tree结构,那么不必遍历整棵树就可以啦!这就是exists比in速度快来的原因!
select CityNam from CityInfo where Exists
(slect CityID from PPL where P_ID like '4418811983%' and CityInfo.CityID = PPL.CityID)
--这句只管到where,所以遍历CityInfo,只要找到一个CityID对应在表PPL中有P_ID like '4418811983%'就select 出来,否则就继续,没有next掉!
select CityNam from CityInfo where CityID in
(select CityID from PPL where P_ID like '4418811983%')
--这个语句,先执行子查询select CityID from PPL where P_ID like '4418811983%',所有的结果出来后,放在一个临时表(‘441881*****’,‘441881*****’,....,‘441881*****’)
然后才去执行主查询select CityNam from CityInfo,综合速度就比前面慢,然后才要去查询对应的
CityID是否存在(‘441881*****’,‘441881*****’,....,‘441881*****’)当中!
因此,使用EXISTS比使用IN通常查询速度快。大多数人会使用in,因为它比较容易编写,不过为了更好的效率还是改为用exists,如果是not in,也尽量改为用not exists,虽然两者都因为用了not(不能用索引而速度变慢),但是not exists 的效率也比not in来得高,如果not in('a','b',null)那么not in 失效,这个也是我们应该采用not exists的原因!
FYI~