天天看点

mysql查询 is null 速度太慢_【SQL】sql查询is not null速度慢的一种处理方式

数据库连表查询中的nvarchar类型字段,tb_Users.Certificatesis not null条件,is not null 会导致查询速度慢很多(因为和“=”号条件遍历方式不一样)。

替换为 “LEN(tb_Users.Certificates) >0”,利用 Users.Certificates为空时整个计算返回false,达到筛选效果。有其他更好的处理方式,有兴趣可以留言讨论一下。

当然,datetime类型也是可以用这个方式的:

declare @test datetime

set @test=getdate()

if(LEN(@test) >0)

begin

print 'true'

end

else

begin

print 'false'

end

结果为true.

declare @test datetime

set @test=null

if(LEN(@test) >0)

begin

print 'true'

end

else

begin

print 'false'

end

结果为false.

原因:

使用LEN(tb_Users.Certificates) >0只有1次扫描,44物理查找执行:

mysql查询 is null 速度太慢_【SQL】sql查询is not null速度慢的一种处理方式

用is not null ,43物理扫描,352物理查找执行

mysql查询 is null 速度太慢_【SQL】sql查询is not null速度慢的一种处理方式

--查看sql执行时间

SET STATISTICS PROFILE ON

SET STATISTICS IO ON

SET STATISTICS TIME ON

--执行的sql语句

SET STATISTICS PROFILE OFF

SET STATISTICS IO OFF

SET STATISTICS TIME OFF