如何遍历 table 中的行作为树
How to traverse rows in a table as a Tree
我有一个包含两列的 table:child
和 parent
。 table 表示具有多棵树的树类结构。给定任何 child,我需要找到它的根。换句话说,我需要获取 child 的 parent,然后是 parent 的 parent,依此类推,直到到达 [=22] 的根=].
child parent
1 2
2 3
9 10
3 4
4 5
5 255
在这里,我们有两棵树。一个从 255(根)开始到 1(叶)结束。
255 -> 5 -> 4 -> 3 -> 2 -> 1
。第二个从 10 开始到 9 结束。例如:如果给出 3
那么它需要找到根,在这种情况下是 255。
我真的是 SQL 世界的新手。我的想法是递归遍历 child 的 parent
列,直到 child
列中没有条目 parent 和 return 那 parent。在 SQL 中有没有办法做到这一点,尤其是在 postgres 中?
对于这种情况,您可以使用递归查询。唯一的问题是递归查询在 Postgres 中不是很有效,所以你只能对少量数据使用这种方法。
这是示例:
create table tree (id integer, parent integer);
insert into tree values(1, null);
insert into tree values(2, 1);
insert into tree values(3, 1);
insert into tree values(4, 3);
insert into tree values(5, 2);
insert into tree values(10, null);
insert into tree values(20, 10);
insert into tree values(30, 10);
insert into tree values(40, 30);
insert into tree values(50, 20);
with recursive parentsearch as (
select id, parent as parent_id from tree where id = :leaf_id
union
select t.id, t.parent as parent_id from tree t join parentsearch ps on t.id=ps.parent_id
)
select * from parentsearch where parent_id is null;
我有一个包含两列的 table:child
和 parent
。 table 表示具有多棵树的树类结构。给定任何 child,我需要找到它的根。换句话说,我需要获取 child 的 parent,然后是 parent 的 parent,依此类推,直到到达 [=22] 的根=].
child parent
1 2
2 3
9 10
3 4
4 5
5 255
在这里,我们有两棵树。一个从 255(根)开始到 1(叶)结束。
255 -> 5 -> 4 -> 3 -> 2 -> 1
。第二个从 10 开始到 9 结束。例如:如果给出 3
那么它需要找到根,在这种情况下是 255。
我真的是 SQL 世界的新手。我的想法是递归遍历 child 的 parent
列,直到 child
列中没有条目 parent 和 return 那 parent。在 SQL 中有没有办法做到这一点,尤其是在 postgres 中?
对于这种情况,您可以使用递归查询。唯一的问题是递归查询在 Postgres 中不是很有效,所以你只能对少量数据使用这种方法。 这是示例:
create table tree (id integer, parent integer);
insert into tree values(1, null);
insert into tree values(2, 1);
insert into tree values(3, 1);
insert into tree values(4, 3);
insert into tree values(5, 2);
insert into tree values(10, null);
insert into tree values(20, 10);
insert into tree values(30, 10);
insert into tree values(40, 30);
insert into tree values(50, 20);
with recursive parentsearch as (
select id, parent as parent_id from tree where id = :leaf_id
union
select t.id, t.parent as parent_id from tree t join parentsearch ps on t.id=ps.parent_id
)
select * from parentsearch where parent_id is null;