Postgresql 按向上投票对树进行排序
我正在写一个评论系统。我已经能够在这里获得教程之后的层次结构() 然而,我很难按向上投票的顺序排列这一行。我不能简单地按路径排序,因为同一线程上的回复将具有不同的节点路径<代码>节点路径使用Postgresql 按向上投票对树进行排序,postgresql,tree,hierarchy,ltree,Postgresql,Tree,Hierarchy,Ltree,我正在写一个评论系统。我已经能够在这里获得教程之后的层次结构() 然而,我很难按向上投票的顺序排列这一行。我不能简单地按路径排序,因为同一线程上的回复将具有不同的节点路径节点路径使用公钥计算 举例说明 a (0 upvotes) -> b (0 upvotes) -> c (1 upvote) d (1 upvote) -> e (0 upvotes) bac的节点路径将分别为a.b和a.c。我不能简单地从节点路径中减去b和c,然后按它们排序。如果我这样做,将导致以下顺序:
公钥
计算
举例说明
a (0 upvotes)
-> b (0 upvotes)
-> c (1 upvote)
d (1 upvote)
-> e (0 upvotes)
b
ac
的节点路径将分别为a.b
和a.c
。我不能简单地从节点路径中减去b
和c
,然后按它们排序。如果我这样做,将导致以下顺序:
a
d
-> b
-> c
-> e
这是有意义的,因为如果从节点路径
中删除每一行的公钥
,它只会按最短的节点路径
排序到最长的
如何编写一个查询,以获得正确的层次结构,并按向上投票排序,如下所示:
d (1)
-> e (0)
a (0)
-> c (1)
-> b (0)
假设向上投票计数不断变化,并且您通过
ltree
路径来避免递归,我想不出一个解决方案,它不需要递归,因为每一行都需要访问其祖先的向上投票计数,才能在结果中找到自己的位置
with recursive base as (
select node_path, upvotes,
array[row_number() over (order by upvotes desc, node_path)] as sort_path
from comment_table
where nlevel(node_path) = 1
union all
select c.node_path, c.upvotes,
p.sort_path||row_number() over (order by c.upvotes desc, c.node_path)
from base p
join comment_table c
on subpath(c.node_path, 0, -1) = p.node_path
)
select * from base order by sort_path;
node_path | upvotes | sort_path
-----------+---------+-----------
d | 1 | {1}
d.e | 0 | {1,3}
a | 0 | {2}
a.c | 1 | {2,1}
a.b | 0 | {2,2}
(5 rows)
伙计,你帮我解决了postgreSQL中的一个复杂问题,在过去的4-5天里,我一直在为一个平台苦苦挣扎。你太棒了。
with recursive base as (
select node_path, upvotes,
array[row_number() over (order by upvotes desc, node_path)] as sort_path
from comment_table
where nlevel(node_path) = 1
union all
select c.node_path, c.upvotes,
p.sort_path||row_number() over (order by c.upvotes desc, c.node_path)
from base p
join comment_table c
on subpath(c.node_path, 0, -1) = p.node_path
)
select * from base order by sort_path;
node_path | upvotes | sort_path
-----------+---------+-----------
d | 1 | {1}
d.e | 0 | {1,3}
a | 0 | {2}
a.c | 1 | {2,1}
a.b | 0 | {2,2}
(5 rows)