How do I fix a Postgres 12 Error: set-returning functions are not allowed in CASE

How do I fix a Postgres 12 Error: set-returning functions are not allowed in CASE

我刚刚将我的 Postres 从 9.1 更新到 12,现在我从特定查询中收到此错误消息:

SQLSTATE[0A000]: Feature not supported: 7 ERROR: set-returning functions are not allowed in CASE LINE 17: generate_series(start_date, ^ HINT: You might be able to move the set-returning function into a LATERAL FROM item.

生成该错误的实际查询是更大的查询的一部分,但实际行是:

CASE
    WHEN num_payments > 1 THEN
        generate_series(start_date, start_date + ((payment_interval*(num_payments-1)) || payment_interval2)::interval, (payment_interval::text || payment_interval2)::interval)::date
    ELSE
        start_date
END

第一次看到这个消息,不知道是什么意思。我如何move the set-returning function into a LATERAL FROM item如错误消息提示?

这就是所谓的 "Lateral Join" -- 基本上它是一个计算列,对您当前的查询来说是 "cross joined"。

这样使用:

SELECT MY_LATERAL,
     -- etc other columns 
FROM YOUR_TABLE 
  LATERAL (CASE
           WHEN num_payments > 1 THEN
             generate_series(start_date, start_date + ((payment_interval*(num_payments-1)) || payment_interval2)::interval, (payment_interval::text || payment_interval2)::interval)::date
           ELSE start_date
           END) AS MY_LATERAL

文档https://www.postgresql.org/docs/9.4/queries-table-expressions.html第 7.2.1.5 节

出于某种原因,我无法使用 LATERAL,因为它刚刚生成了其他语法错误消息(我将不得不在长 运行 上处理它)。所以我能够通过简单地选择所有值然后在查询中将 CASE 向上移动以便 generate_series() 不在 case 语句中来解决我的问题:

SELECT other_columns, 
       CASE
           WHEN num_payments > 1 THEN date_2 ELSE date_1
       END AS start_date
FROM(
       SELECT other_columns, 
              start_date AS date_1,
              generate_series(start_date, start_date + ((payment_interval*(num_payments-1)) || payment_interval2)::interval, (payment_interval::text || payment_interval2)::interval)::date AS date_2
       FROM(
           -- INNER QUERY
       )a
)b