首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >侧向PostgreSQL替代方案

侧向PostgreSQL替代方案
EN

Stack Overflow用户
提问于 2019-07-09 22:15:42
回答 1查看 29关注 0票数 0

我在PostgreSQL数据库中运行了一个相当复杂的查询,它执行一大堆求和、计算等操作。

其中一个表包含3个不同的日期,并且根据它们的值,只选择其中一个。然后在该特定行的计算中使用它数十次,甚至数百次。我可以使用如下所示的CASE语句选择正确的日期:

代码语言:javascript
复制
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

正如我所说的,这个东西被多次使用,所以在查询中复制和粘贴它是相当疯狂的。相反,我将其写为横向连接,如下所示:

代码语言:javascript
复制
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语句会显著降低应用程序的运行速度。有没有更好/更聪明的方法来达到与横向复制相同的效果,但在不牺牲速度的情况下避免巨大的复制/粘贴?

EN

回答 1

Stack Overflow用户

发布于 2019-07-09 22:21:20

您可以将原始查询包装在派生表中,在那里计算CASE表达式,并在外部查询中使用结果

代码语言:javascript
复制
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 = ...;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56954601

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档