我正在为论坛开发一个数据库,其中包含线程和消息。线程以一条没有消息的消息开始parent_id
;回复是消息parent_id
.
我有一张消息表。每个项目都引用同一个表上的项目,将它们作为父子关系。
create table messages(
id int,
title text,
content text,
parent_id int
);
现在我用一些数据填充表格:
insert into messages values
(1, 'One', 'First thread main post', null), -- First thread
(2, 'Two', 'First thread reply', 1),
(3, 'Three', 'First thread reply', 2),
(4, 'Four', 'Second thread main post', null), -- Second thread
(5, 'Five', 'Second thread reply', 4),
(6, 'Six', 'Second thread reply', 5),
(7, 'Six', 'Second thread reply', 6),
(8, 'Six', 'Second thread reply', 7),
(9, 'Six', 'Second thread reply', 8);
知道id
对于线程的第一条消息,我可以使用递归查询检索所有回复:
with recursive my_tree as (
select * from messages
where parent_id IS null and id = 4
union all
select messages.* from messages
join my_tree on messages.parent_id = my_tree.id
) select my_tree.*
from my_tree;
这里有一个.
现在,假设我知道id
一些答复,我想得到id
线程的第一条消息。我该怎么做?
编辑:
我知道我可以从已知的线程中检索所有消息id
向上:
with recursive my_tree as (
select * from messages
where id = 9
union all
select messages.* from messages
join my_tree on messages.id = my_tree.parent_id
) select my_tree.*
from my_tree;
Here a 但如果线程由数千条消息组成,效率就会降低。有没有什么方法可以让递归查询到达第一项而不检索所有消息?