此问题在此处已有答案:
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;
但这是行不通的。那么有没有办法做到这一点?如果有,怎么做?
1条答案
按热度按时间oalqel3c1#
从
WITH RECURSIVE
开始。您仍然可以添加非递归CTE:小提琴
请参阅: