当前位置: 移动技术网 > IT编程>数据库>MSSQL > SQL语句NOT IN优化之换用NOT EXISTS

SQL语句NOT IN优化之换用NOT EXISTS

2018年09月30日  | 移动技术网IT编程  | 我要评论

晚娘2qvod,最新的人民币第6套,thinkpad t400s

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慢。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网