SQL语句NOT IN优化之换用NOT EXISTS
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慢。