我在PostgreSQL数据库中运行了一个相当复杂的查询,该查询执行了大量的求和,计算等工作。
其中一个表包含3个不同的日期,并且根据它们的值,只选择其中一个。然后在该特定行的计算中将其使用数十甚至数百次。我可以使用如下的CASE
语句来选择正确的日期:
case
when promotion_date is null and offboard_date is null then current_date::date
when promotion_date is null then offboard_date
else promotion_date end
正如我所说,这个东西被多次使用了,所以在整个查询中复制并粘贴它是相当疯狂的。相反,我将其写为LATERAL联接,如下所示:
LEFT JOIN LATERAL ( SELECT (case
when promotion_date is null and offboard_date is null then current_date::date
when promotion_date is null then offboard_date
else promotion_date end) AS date
FROM promotions) AS promotionDate ON true
所以现在我可以在计算中使用promotionDate.date
了,它更短并且易于阅读。
但是,由于该分支是针对每个单独的行执行和计算的,并且我也有很多分支,因此以这种方式编写查询,而不是在整个位置复制/粘贴CASE
语句会大大减慢速度应用程序。有没有更好/更聪明的方法来获得与侧边相同的效果,但又避免了在不牺牲速度的同时避免巨大的复制/粘贴?
答案 0 :(得分:0)
您可以将原始查询包装在派生表中,在那里评估CASE表达式,然后在外部查询中使用该结果
select ... other columns ...,
calculated_date --<< this is now the result of the CASE expression
from (
select .... ,
case
when promotion_date is null and offboard_date is null then current_date::date
when promotion_date is null then offboard_date
else promotion_date
end as calculated_date
from ...
join ...
where
) as t
where calculated_date = ...;