简体   繁体   English

SQL:递归选择所有子记录的SUM

[英]SQL: Select SUM of all children records recursively

I have a table that has a one to many relationship with itself. 我有一张与自己有一对多关系的桌子。 Each record can have n number of children from that same table. 每条记录可以有同一个表中的n个子项。 For example 例如

create table folder
ID: Number 20 PK
PARENT_ID: Number 20 FK references folder.ID
SIZE: NUMBER 20
...

Given an ID, I want to select the SUM(SIZE) of all folder records recursively. 给定一个ID,我想以递归方式选择所有文件夹记录的SUM(SIZE)。 The target database is MySql 5, but it would be nice if it was generic enough to work in Oracle and MS-SQL as well. 目标数据库是MySql 5,但如果它足够通用以便在Oracle和MS-SQL中工作,那将是很好的。

I won't know how deep the tree is, could be 1 level, could be 50 (or more) 我不知道树有多深,可能是1级,可能是50级(或更多)

This may be some some assistance: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ 这可能是一些帮助: http//mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

This would be a simple query in Oracle ( http://download-east.oracle.com/docs/cd/B12037_01/server.101/b10759/queries003.htm ) since it supports hierarchical queries using "CONNECT BY" but I don't think there's a comparable solution for MySQL. 这将是Oracle中的简单查询( http://download-east.oracle.com/docs/cd/B12037_01/server.101/b10759/queries003.htm ),因为它支持使用“CONNECT BY”进行分层查询但我不喜欢我认为有一个类似的MySQL解决方案。 It looks like you're going to do something really inefficient or you're going to have to modify your table structure to support this specific function. 看起来你会做一些非常低效的事情,或者你将不得不修改你的表结构以支持这个特定的功能。

一种解决方案是在表“topmost_parent”中添加一列并加入其中。

You should consider re-structuring the data using a nested set model. 您应该考虑使用嵌套集模型重新构建数据。 The following link describes how to do it: 以下链接介绍了如何执行此操作:

http://www.vbmysql.com/articles/database-design/managing-hierarchical-data-in-mysql http://www.vbmysql.com/articles/database-design/managing-hierarchical-data-in-mysql

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM