我正在使用 Postgres 9.1,并且我有一个带有家谱层次结构的表。此表称为父母,其中有两个外键,一个用于父级,一个用于关系中的子级。以下 SQL 查询(大部分是从 Postgres 文档中窃取的)可以工作,但会向上和向下遍历树:
with recursive temp(child, parent, depth, path, cycle) as
(select child, parent, 1, array[child], false
from parents
where parent = 149
union all
select parents.child, parents.parent, temp.depth + 1, path || parents.child, parents.child = any(path)
from temp, parents
where parents.child = temp.parent)
select distinct c1.name as child_name, c2.name as parent_name
from temp
join people c1 on temp.child = c1.id
join people c2 on temp.parent = c2.id;
父节点 149 是遍历的根节点。
输出有 149 个子代和所有代的祖先。理想情况下,查询将沿家谱下降,并且没有祖先的代。