上一篇《对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的性能好很多。

相关文章:

  • 2021-11-20
  • 2022-03-01
  • 2021-07-11
猜你喜欢
  • 2021-08-09
  • 2021-06-19
  • 2021-08-27
  • 2022-12-23
  • 2021-10-15
  • 2021-10-16
  • 2021-11-28
相关资源
相似解决方案