在表中计算分层数据的所有子节点数量

5
我想要计算一个表中维护的树形结构(父子键)下任何级别的所有子节点数量。该表的结构和数据如下所示:

id -  item-   parentid    
1  -  A   -   
2  -  B   -   1   
3  -  C   -   1   
4  -  D   -   2   
5  -  E   -   2   
6  -  F   -   3   
7  -  G   -   3   
8  -  H   -   5   
9  -  I   -   5   
10 -  J   -   9   
11 -  K   -   4   

例如,B具有以下子代和孙代结构:
  • B
    • E
      • H
      • I
        • J
    • F
      • K
现在,如果您想计算"B的所有子节点",我的答案应该是6。
任何基于纯SQL查询的解决方案都将非常有帮助。或者mysql / php也可以使用。
谢谢!

有许多不同的方法可以实现这一点,我已经在https://dev59.com/YVfUa4cB1Zd3GeqPFSw0上发布了答案。为了确定哪种方法是适当的,我们需要知道您想从此表中获取什么样的信息,以及表格更新的频率--信息添加和删除的频率,如果从层次结构的中间删除了某些内容,应该发生什么。您能详细说明一下您想要用这个层次结构做什么吗? - Ken Bloom
在SQL平台上,这很简单,解决方案使用递归。但对于像您这样的非SQL平台以及没有递归的平台,您必须使用存储过程和临时表。 - PerformanceDBA
我有一个使用php和MySql的解决方案,请查看我的回答。我使用一次查询获取树形结构,并实现两个递归函数来计算树中每个节点的所有子节点数(分层数据结构)。 - nachospiu
3个回答

3
以下是基于PHP的解决方案:
function countChildren($startId) {
    $directDescendents = *_query("SELECT id FROM Table WHERE parentid = ?", array( $startId ));
    $count = *_num_rows($directDescendents);
    while($row = *_fetch_array($directDescendents))
        $count += countChildren($row['id']);
    return $count;
}

$numChildren = countChildren(2); // Number of Children for 'B'

使用您正在使用的SQL扩展程序中的任何函数替换*_num_rows*_fetch_array。 这不像纯SQL解决方案那样高效,但可以工作。 我在函数中查询的方式假设有绑定参数,但您可以根据需要执行查询。


1
根据表的大小和分支的深度,检索整个表并在内存中进行遍历/计数可能比发出多个选择语句更有效(反之亦然)。 - Unreason

3

可以通过一个非递归存储过程来相对简单地完成,具体如下:

示例调用

mysql> call category_hier(1);
+--------------+
| num_children |
+--------------+
|            3 |
+--------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> call category_hier(2);
+--------------+
| num_children |
+--------------+
|            2 |
+--------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

完整脚本

drop table if exists categories;
create table categories
(
cat_id smallint unsigned not null auto_increment primary key,
name varchar(255) not null,
parent_cat_id smallint unsigned null,
key (parent_cat_id)
)
engine = innodb;

insert into categories (name, parent_cat_id) values
('Location',null), 
('Color',null), 
   ('USA',1), 
      ('Illinois',3), 
      ('Chicago',3), 
   ('Black',2), 
   ('Red',2);


drop procedure if exists category_hier;
delimiter #

create procedure category_hier
(
in p_cat_id smallint unsigned
)
begin

declare v_done tinyint unsigned default 0;
declare v_depth smallint unsigned default 0;

create temporary table hier(
 parent_cat_id smallint unsigned, 
 cat_id smallint unsigned, 
 depth smallint unsigned default 0
)engine = memory;

insert into hier select parent_cat_id, cat_id, v_depth from categories where cat_id = p_cat_id;
create temporary table tmp engine=memory select * from hier;

/* http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html */

while not v_done do

    if exists( select 1 from categories c
        inner join tmp on c.parent_cat_id = tmp.cat_id and tmp.depth = v_depth) then

        insert into hier select c.parent_cat_id, c.cat_id, v_depth + 1 from categories c
            inner join tmp on c.parent_cat_id = tmp.cat_id and tmp.depth = v_depth;

        set v_depth = v_depth + 1;          

        truncate table tmp;
        insert into tmp select * from hier where depth = v_depth;

    else
        set v_done = 1;
    end if;

end while;

/*
select 
 c.cat_id,
 c.name as category_name,
 p.cat_id as parent_cat_id,
 p.name as parent_category_name,
 hier.depth
from 
 hier
inner join categories c on hier.cat_id = c.cat_id
left outer join categories p on hier.parent_cat_id = p.cat_id
order by
 hier.depth;
*/

select count(*) as num_children from hier where parent_cat_id is not null;

drop temporary table if exists hier;
drop temporary table if exists tmp;

end #

delimiter ;

call category_hier(1);

call category_hier(2);

你可以很容易地调整此示例以满足你的需求。
希望这能帮到你 :)

3

3
请问需要翻译成哪种语言呢? - Unreason
@Unreason 是的,我已经看过那篇文章很多次了,但现在不记得了。;D - Yoshi
@Unreason,Yoshi:它在这个位置消失了,这是新的链接:http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/。 - Paŭlo Ebermann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接