我有一个评论树及其关闭表:
create table comment (
id serial primary key,
author varchar(100) not null,
content text not null
);
create table closure (
ancestor integer not null references comment (id),
descendant integer not null references comment (id) on delete cascade,
depth integer not null,
primary key (ancestor, descendant)
);
我想在 ID 的评论下获取所有评论的子树4
。对评论线程进行广度优先遍历并不难:
select comment.*, closure.depth
from comment
inner join closure on closure.descendant = comment.id
where ancestor = 4
order by depth asc;
如何对评论线程进行预排序(深度优先)遍历?
(我意识到使用嵌套集很容易进行预订遍历,但我特别好奇如何使用闭包表进行遍历。)