2014-02-18 41 views
3

在PostgreSQL使用使用RECURSIVE WITH的內側,帶可以由另一個與其一起使用,例如:PostgreSQL中

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

再就是RECURSIVE WITHs,其可以像這樣進行:

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

但是到目前爲止,我還沒有找到使用先前WITH的RECURSIVE 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; 

但這不起作用。那麼有沒有辦法做到這一點?如果是這樣,怎麼樣?

回答

3

開始於WITH RECURSIVE。您仍然可以遞歸部分之前擠進「正規」的熱膨脹係數:

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 * FROM num2) 
    ) 
SELECT sum(n) FROM t; 

-> SQLfiddle demo.