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