使用Postgres的递归树总和?
我有一个看起来像这样的树结构:
root
A B
A1 A2 B1 B2
A1.1 A1.2 A2.1 B1.1
桌子看起来像这样:
id | name |value | parent_id
1 root null null
2 A null 1
3 B null 1
4 A1 null 2
5 A1.1 2 4
6 A1.2 3 4
.........................
非叶子节点必须包含他们孩子的叶子节点的总和。
我该如何通过快速的Postgres查询来实现此目标
I have a tree structure that looks like this:
root
A B
A1 A2 B1 B2
A1.1 A1.2 A2.1 B1.1
the table looks something like this:
id | name |value | parent_id
1 root null null
2 A null 1
3 B null 1
4 A1 null 2
5 A1.1 2 4
6 A1.2 3 4
.........................
the non leaf nodes must contain the sum of their children leaf nodes.
how can i achieve this with a fast Postgres query
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如我评论时,如果表中只有一个根节点,则只需使用
sum
of Value>,您可以尝试使用CTE递归来获取要
sum
As I comment, If there is only one root node in your table you can just use
sum
of valueOr you can try to use CTE RECURSIVE to get which root node you want to
SUM
sqlfiddle
更新24-04-2022
用递归cte , “ https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.8.30.16
” //www.db-fiddle.com/f/my4cvmmaifkoehsgfczfgv/2“ rel =“ nofollow noreferrer”> db小提琴演示
update 24-04-2022
Solution with recursive CTE, arrays and ANY()
DB Fiddle demo