我有一个运行很长时间的SQL查询。问题是它使用了一个join case case语句。有什么方法可以优化以下查询:
Select A.Field1, A.load_date, B.field3 from A left outer join B
on (A.field_date between B.start_date and B.end_date)
AND
case
When (A.field1=1) Then (A.field2 = B.field2 and A.field3 = B.field3)
When (A.field1=2) Then (A.field2 = B.field2)
Else (A.field3 = B.field3)
End
有人可以建议一些调整,因为此查询需要数小时才能运行。我必须找到一些较短的版本。
答案 0 :(得分:0)
这是一个开始:
Select A.Field1, A.load_date, B.field3
from A
left outer join B
on (A.field_date between B.start_date and B.end_date)
and (A.field2 = B.field2 and A.field3 = B.field3)
where A.field1 = 1
union all
Select A.Field1, A.load_date, B.field3
from A
left outer join B
on (A.field_date between B.start_date and B.end_date)
and (A.field2 = B.field2)
where A.field1 = 2
union all
Select A.Field1, A.load_date, B.field3
from A
left outer join B
on (A.field_date between B.start_date and B.end_date)
and (A.field3 = B.field3)
where (A.field1 <> 1 and A.field1 <> 2)
由于您的三个案例都是互斥的,因此它们可以表示为3个单独的查询,这些查询一起是UNION。 UNION ALL意味着不会检查重复项 - 但由于没有记录可以满足多组标准,因此不应该有任何重复项。
这将删除您的CASE语句,并允许更好地优化查询路径。毫无疑问,其他人会有更多建议。