SQL语句NOT IN优化之换用NOT EXISTS
程序员文章站
2024-03-31 12:20:28
NOT IN查询示例(示例背景描述:根据条件查询Questions表得到的数据基本在PostedData表中不存在,为完全保证查询结果在PostedData表中不存在,使用NOT IN): 查询耗时如图: 换用NOT EXISTS 查询示例: 查询耗时如图: 根据查询耗时明显可以看出,使用 NOT ......
not in查询示例(示例背景描述:根据条件查询questions表得到的数据基本在posteddata表中不存在,为完全保证查询结果在posteddata表中不存在,使用not in):
set statistics profile on; set statistics io on; set statistics time on; go /*--你的sql脚本开始*/ select a.id from dbo.questions a with ( nolock ) where a.questionstate = '正常' and a.checktime > '2018-09-29 16:00:00' and a.stateshowid not in ( select b.intid from dbo.posteddata b where b.[type] = 'question' ); /*你的sql脚本结束*/ go set statistics profile off; set statistics io off; set statistics time off;
查询耗时如图:
换用not exists 查询示例:
set statistics profile on; set statistics io on; set statistics time on; go /*--你的sql脚本开始*/ select a.id from dbo.questions a with ( nolock ) where a.questionstate = '正常' and a.checktime > '2018-09-29 16:00:00' and not exists ( select b.intid from dbo.posteddata b where b.[type] = 'question' and a.stateshowid = b.intid ); /*你的sql脚本结束*/ go set statistics profile off; set statistics io off; set statistics time off;
查询耗时如图:
根据查询耗时明显可以看出,使用 not exists 比not in 的查询速度快很多。
but,我做了其他条件下的一些实验,发现根据条件查询a表得到的结果,在b表中存在时,两种查询的查询速度差异不大。还有一些情况not exists的查询速度比not in慢。
推荐阅读
-
SQL语句NOT IN优化之换用NOT EXISTS
-
sql server 性能优化之nolock
-
mysql sql语句优化(sql和python的区别讲解)
-
mysql sql语句优化(sql和python的区别讲解)
-
sql server之T-SQL语句创建数据库创建表
-
(转)数据库SQL优化大总结之 百万级数据库优化方案 博客分类: 其他 sql优化
-
SQL语句优化 博客分类: SQL sqlcountinexist
-
SQL语句优化 博客分类: SQL sqlcountinexist
-
[一起学Hive]之十二-Hive SQL的优化 博客分类: hive 一起学hivehive优化
-
SQL语句 之 表的操作