2015-04-29 82 views
2

我有遞歸查詢檢索特定的人PostgreSQL中的遞歸查詢。 SELECT *

WITH RECURSIVE recursetree(id, parent_id) AS (
    SELECT id, parent_id FROM tree WHERE parent_id = 0 
    UNION 
    SELECT t.id, t.parent_id 
    FROM tree t 
    JOIN recursetree rt ON rt.id = t.parent_id 
) 
SELECT * FROM recursetree; 

正如你所看到的,我指定的列清單要檢索的所有兒童。但我想用SELECT *(我在真正的桌子上有很多列,他們可以在將來改變)。有沒有辦法讓所有列沒有單獨定義每個列?

回答

1

你並不需要在WITH部分指定列。如果您不說,列名將由UNION中的第一個查詢確定:

WITH RECURSIVE recursetree AS (
    SELECT * FROM tree WHERE parent_id = 0 
    UNION 
    SELECT t.* 
    FROM tree t 
    JOIN recursetree rt ON rt.id = t.parent_id 
) 
SELECT * 
FROM recursetree; 
+0

您的清潔器!我不知道中間CTE對象是否會「更胖」會影響性能,(我恐怕會這樣) – wildplasser

+0

@wildplasser:只有一個'explain(analyze,verbose)'可以告訴;) –

+0

但我太懶惰建立一個測試臺。我必須輸入所有列名稱! http://www.catb.org/jargon/html/R/recursion.html – wildplasser

1

快速劈飛(與原歸隊):

WITH RECURSIVE recursetree(id, parent_id) AS (
    SELECT id, parent_id FROM tree WHERE parent_id = 0 
    UNION 
    SELECT t.id, t.parent_id 
    FROM tree t 
    JOIN recursetree rt ON rt.id = t.parent_id 
) 
SELECT * 
FROM tree tr 
WHERE EXISTS (SELECT 1 
    FROM recursetree x 
    WHERE x.id = tr.id 
    );