在PostgreSQL中的RECURSIVE WITH内使用WITH [重复]

jgzswidk  于 2022-12-03  发布在  PostgreSQL
关注(0)|答案(1)|浏览(270)

此问题在此处已有答案

Issue with recursive CTE in PostgreSQL(1个答案)
How to use multiple CTEs in a single SQL query?(4个答案)
八年前就关门了。
在PostgreSQL中,一个WITH可以由另一个WITH使用,例如:

WITH num AS (
    VALUES (50)
), num2 AS (
    SELECT column1 * 2 AS value FROM num
)
SELECT value FROM num2;

然后是RECURSIVE WITH,它可以这样做:

WITH RECURSIVE t(n) AS (
    VALUES (1)
  UNION ALL
    SELECT n+1 FROM t WHERE n < 100
)
SELECT sum(n) FROM t;

但到目前为止,我还没有找到一种方法让递归WITH使用先前的WITH。我认为应该是这样的:

WITH num AS (
    VALUES (50)
), num2 AS (
    SELECT column1 * 2 AS value FROM num
), RECURSIVE  t(n) AS (
        VALUES (1)
    UNION ALL
        SELECT n+1 FROM t WHERE n < (SELECT * FROM num2)
)
SELECT sum(n) FROM t;

但这是行不通的。那么有没有办法做到这一点?如果有,怎么做?

oalqel3c

oalqel3c1#

WITH RECURSIVE开始。您仍然可以添加非递归CTE:

WITH RECURSIVE
   num  AS (VALUES (50))
,  num2 AS (SELECT column1 * 2 AS value FROM num)
,  t(n) AS (
      VALUES (1)
      UNION ALL
      SELECT n+1 FROM t WHERE n < (SELECT value FROM num2)
   )
SELECT sum(n) FROM t;

小提琴
请参阅:

  • 如何在单个SQL查询中使用多个CTE?

相关问题