如何获得PostgreSQL中最顶级的父级

时间:2010-05-18 08:47:42

标签: postgresql

我有一个带有列的树结构表: ID,父名。 给定树A-> B-> C, 我如何根据C的ID获得最顶级的父母A的身份证? 特别是如何用“with recursive”编写SQL? 谢谢!

2 个答案:

答案 0 :(得分:4)

要实现递归查询,您需要Common Table Expression(CTE)。 此查询计算所有父节点的祖先。由于我们只想要顶级,我们选择level = 0。

WITH RECURSIVE Ancestors AS
(
   SELECT id, parent, 0 AS level FROM YourTable WHERE parent IS NULL
   UNION ALL
   SELECT child.id, child.parent, level+1 FROM YourTable child INNER JOIN
      Ancestors p ON p.id=child.parent

)
SELECT * FROM Ancestors WHERE a.level=0 AND a.id=C

如果要获取所有数据,请在ID上使用内部联接,例如

SELECT YourTable.* FROM Ancestors a WHERE a.level=0 AND a.id=C
   INNER JOIN YourTable ON YourTable.id = a.id

答案 1 :(得分:3)

WITH    RECURSIVE q AS
        (
        SELECT  m
        FROM    mytable m
        WHERE   id = 'C'
        UNION ALL
        SELECT  m
        FROM    q
        JOIN    mytable m
        ON      m.id = q.parent
        )
SELECT  (m).*
FROM    q
WHERE   (m).parent IS NULL