Sql IsNull很慢,我还有其他选择吗?
具有以下查询:Sql IsNull很慢,我还有其他选择吗?,sql,sql-server,Sql,Sql Server,具有以下查询: select tA.Name ,tA.Prop1 ,tA.Prop2 ( select sum(tB.Values) from tableB tB where tA.Prop1 = tB.Prop1 and tA.Prop2 = tB.Prop2 ) as Total from tableA tA 运行此查询需要1秒,但当Prop2为空时,它将给
select
tA.Name
,tA.Prop1
,tA.Prop2
( select sum(tB.Values)
from tableB tB
where tA.Prop1 = tB.Prop1
and tA.Prop2 = tB.Prop2
) as Total
from tableA tA
运行此查询需要1秒,但当Prop2为空时,它将给我错误的总和
我将查询更改为使用IsNULL
and ISNULL(tA.Prop2,-1) = ISNULL(tB.Prop2,-1)
数据现在是正确的,但几乎需要7秒
有没有最快的方法
注意:这只是更复杂查询的部分简化版本。。。。但是基本思想就在这里。根据您的描述,
=
正在使用索引,但是isnull()
阻止了索引的使用。这在SQLServer中有点难以实现
一种方法是将逻辑分解为两个和:
select tA.Name, tA.Prop1, tA.Prop2
(isnull((select sum(tB.Values)
from tableB tB
where tA.Prop1 = tB.Prop1 and tA.Prop2 = tB.Prop2
), 0) +
isnull((select sum(tB.Values)
from tableB tB
where tA.Prop1 = tB.Prop1 and
tA.Prop2 is null and tB.Prop2 is null
), 0)
) as Total
from tableA tA;
我最终使用了
AND (
(tA.Prop2= tB.Prop2)
OR (tA.Prop2 IS NULL AND tB.Prop2 IS NULL )
)
它们在两个表的
Prop2
上都有索引吗?发布一些示例数据,如果您想检查两列的NULL
,请尝试tA.Prop2为NULL,tB.Prop2为NULL
。这将提供一个可搜索表达式,因为函数未应用于列。