SQL 中复杂的聚合函数和层次结构

发布于 2024-09-19 00:32:24 字数 343 浏览 1 评论 0原文

我想在 SQL 数据库(MySQL,但想避免 DBMS 特定的功能)中存储任意深度的树结构。现在我想计算每个节点的值N,如下所示:

  • 首先,计算当前节点的所有(直接)子节点(即没有子节点)中某一列的总和,
  • 然后,计算剩余每个子节点(即有子节点的子节点)的最大值N
  • ,最后将前两步的结果相加得到N的值当前节点

显然,这涉及递归,因此嵌套集似乎是此场景的选择表示。但是,我不知道如何将上面的计算公式化为 SQL 查询。获得所有后代的 SUM() 或 MAX() 很容易,但聚合函数的组合方式使问题变得非常复杂。有人有解决办法吗?

I want to store a tree structure of arbitrary depth in an SQL database (MySQL, but want to avoid DBMS-specific features). Now I want to compute a value N for each node as follows:

  • first, calculate the sum of a certain column in all (immediate) children of the current node which are leaves (i.e. have no children)
  • then, calculate the maximum of the values N of each of the remaining children, i.e. those with children
  • finally, add the results of the first two steps to get the value N for the current node

Obviously, this involves a recursion, so nested sets seem to be the representation of choice for this scenario. However, I couldn't work out how to formulate the calculation above as an SQL query. It is easy to get the SUM() or MAX() of all the descendants, but the way the aggregate functions are combined complicates the matter greatly. Does anyone have a solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

抽个烟儿 2024-09-26 00:32:24

如果模式还有其他计算列(例如深度和“是叶节点”)怎么办?

它需要更多的维护(并不是说嵌套集是免维护的),但我认为它使用“标准”SQL 可以实现上述查询。

What if the schema also had additional computed columns such as depth and "is leaf node"?

It would require more maintenance (not that nested sets are maintenance free) but I think it puts the above query within reach using "standard" SQL.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文