对SQL查询优化的补充--(exists篇)

Posted on 2010-09-02 11:35  チャチャの楽園  阅读(650)  评论(0编辑  收藏  举报

上一篇《对SQL查询优化的补充--(in篇)》主要讨论select ... from ... where ... in ....这种查询语句。接着我们来讨论一下select ... from ... where ... exists ....这个了。Exists的查询速度要比in强得多,这是众所周知的事,但我们并不可以说完全用exists来代替in。为什么这么说呢?我们先来看看可以用exists来代替in的场合吧。

 

select... from A where id in (select id from B)可以替代为select...from A where exists (select id from B where A.id = id)

not in 的话可以替换成not exists。这是可以使用exists来提高查询性能的场合,接着什么是不能直接替换的场合呢?

 

select...from A where id in (1,2,3,4,5,6....)这种出现零散值的时候就不能直接使用exists来替换了。

如果出现这种情况的话,我的做法是用in和exists结合的办法,就像我在in篇写的使用临时表作为辅佐,先用in把筛选过的数据导进临时表里,然后用临时表跟其他表关联或者使用where exists(select id from #tempTable where A.id = id)这种方法来筛选记录。这样做法往往比一大串的表连接加where in的性能好很多。

Copyright © 2024 チャチャの楽園
Powered by .NET 8.0 on Kubernetes