欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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;

查询耗时如图:

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

换用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;

 查询耗时如图:

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

根据查询耗时明显可以看出,使用 not exists 比not in 的查询速度快很多。

but,我做了其他条件下的一些实验,发现根据条件查询a表得到的结果,在b表中存在时,两种查询的查询速度差异不大。还有一些情况not exists的查询速度比not in慢。