我在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正如我所说的,这个东西被多次使用,所以在查询中复制和粘贴它是相当疯狂的。相反,我将其写为横向连接,如下所示:
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语句会显著降低应用程序的运行速度。有没有更好/更聪明的方法来达到与横向复制相同的效果,但在不牺牲速度的情况下避免巨大的复制/粘贴?
发布于 2019-07-09 22:21:20
您可以将原始查询包装在派生表中,在那里计算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 = ...;https://stackoverflow.com/questions/56954601
复制相似问题