sql语句优化之用EXISTS替代IN、用NOT EXISTS替代NOT IN的语句
在许多基于基础表的查询中,为了满足一个条件,往往需要对另一个表进行联接。在这种情况下, 使用EXISTS(或NOT EXISTS)通常将提高查询的效率。在子查询中,NOT IN子句将执行一个内部的排序和合并。无论在哪种情况下,NOT IN都是最低效的 (因为它对子查询中的表执行了一个全表遍历)。为了避免使用NOT IN ,我们可以把它改写成外连接(Outer Joins)或NOT EXISTS。
如
我要查询 Sendorder表中的冗余数据(没有和reg_person或worksite相连的数据)
sql="select Sendorder.id,Sendorder.reads,Sendorder.addtime from Sendorder where Sendorder.person_id not in(select user_id from reg_person ) or Sendorder.worksite_id not in(select id from worksite) order by Sendorder.addtime desc"
程序执行时间:40109.38毫秒
sql="select Sendorder.id,Sendorder.reads,Sendorder.addtime from Sendorder where not EXISTS (SELECT id FROM reg_person where reg_person.user_id=Sendorder.person_id) or not EXISTS (SELECT id FROM worksite where worksite.id=Sendorder.worksite_id) order by Sendorder.addtime desc"
程序执行时间:8531.25毫秒
很明显使用not EXISTS效率高多了
如
我要查询 Sendorder表中的冗余数据(没有和reg_person或worksite相连的数据)
sql="select Sendorder.id,Sendorder.reads,Sendorder.addtime from Sendorder where Sendorder.person_id not in(select user_id from reg_person ) or Sendorder.worksite_id not in(select id from worksite) order by Sendorder.addtime desc"
程序执行时间:40109.38毫秒
sql="select Sendorder.id,Sendorder.reads,Sendorder.addtime from Sendorder where not EXISTS (SELECT id FROM reg_person where reg_person.user_id=Sendorder.person_id) or not EXISTS (SELECT id FROM worksite where worksite.id=Sendorder.worksite_id) order by Sendorder.addtime desc"
程序执行时间:8531.25毫秒
很明显使用not EXISTS效率高多了
相关推荐
lhxxhl 2020-11-16
minggehenhao 2020-07-28
ItBJLan 2020-06-28
CARBON 2020-06-14
luotuofeile 2020-06-12
xiaobaif 2020-05-09
dreamhua 2020-03-28
huangliang00 2020-02-22
wklken的笔记 2020-02-15
萌亖 2020-02-10
郴州小程序 2020-01-24
liuyang000 2020-01-24
fengdos 2019-12-27
azhou 2019-12-25
oraclemch 2019-12-01
明月清风精进不止 2019-11-30
herohope 2019-10-21