PostgreSQL中的递归查询。选择 *

时间:2015-04-29 12:28:38

标签: postgresql recursion

我有递归查询来检索给定人的所有孩子

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 *(实际表中我有很多列,将来可以更改它们)。有没有办法获得所有列而不单独定义每个列?

2 个答案:

答案 0 :(得分:3)

您无需在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;

答案 1 :(得分:2)

快速破解(与原文重新加入):

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
    );