【发布时间】:2012-08-30 21:47:17
【问题描述】:
树的深度是无限的。示例:
+----+-------+--------------------+
| id | name | parent_id | value |
+----+-------+--------------------+
| 1 | test1 | | 0 |
| 2 | test2 | 1 | 0 |
| 3 | test3 | 2 | 5 |
| 4 | test4 | 1 | 0 |
| 5 | test5 | 4 | 5 |
| 6 | test6 | 4 | 0 |
| 7 | test7 | 6 | 10 |
+----+-------+--------------------+
我想得到一个孩子的总价值。 就像这样:
+----+-------+--------------------+
| id | name | parent_id | value |
+----+-------+--------------------+
| 1 | test1 | | 20 | = test2.value + test4.value
| 2 | test2 | 1 | 5 | = test3.value
| 3 | test3 | 2 | 5 |
| 4 | test4 | 1 | 15 | = test5.value + test6.value
| 5 | test5 | 4 | 5 |
| 6 | test6 | 4 | 10 | = test7.value
| 7 | test7 | 6 | 10 |
+----+-------+--------------------+
有什么建议吗?谢谢!
【问题讨论】:
-
在不知道您的其余需求的情况下,我无法确定正确的模式是什么,但您的实现是一种在数据库中存储树的非常幼稚的方式。已经发明了一些设计模式,可以更容易地做各种聪明的事情,包括你提出的问题。例如,查看物化路径设计模式。请参阅rampant-books.com/book_0601_sql_coding_styles.htm 或其他参考资料。
-
@hims056:有什么不清楚的地方?按照
parent_id链接并递归求和count值。 -
@hims056 第一个表是我拥有的,第二个是我想要创建一个视图
-
我快速谷歌了一下,发现这篇文章几乎就是你的确切用例...ibstaff.net/fmartinez/?p=18
标签: sql postgresql tree count children