的穿越我的意見一棵樹,它的closure table:預購(深度優先)的封閉表
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;
我該怎麼辦預購(深度優先)評論跟帖的穿越?
(我認識到,做一個前序遍歷很容易與嵌套集合,但我很好奇,專門對如何與閉合表做到這一點。)
你爲什麼要存儲深度?這是多餘的,可能是錯誤的。 – 2013-04-23 19:18:06
此外,您顯示的查詢將僅檢索第4條評論,並在第4條評論的「下面」。您需要使用遞歸查詢來檢索整個樹結構。 – 2013-04-23 19:22:14
我不能回答您的查詢,現在(我更熟悉Oracle'連接by'語法),但也許[文件](http://www.postgresql.org/docs/9.2/static/queries- with.html)將幫助你。 – 2013-04-23 19:25:07