Recursive query in PostgreSQL. SELECT *

限于喜欢 提交于 2020-02-21 10:46:06

问题


I have recursive query to retrieve all children of a given person

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;

As you can see, I'm specifying list of columns to be retrieved. But I want to use SELECT * (I have really many columns in real table, and they can be changed in future). Is there some way to get ALL columns without defining each column individually?


回答1:


You don't need to specify the columns in the WITH part. If you leave that out, the column names will be determined by the first query in the 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;



回答2:


quick hack-around (rejoin with the original):

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


来源:https://stackoverflow.com/questions/29943766/recursive-query-in-postgresql-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!