【问题标题】:Count all child nodes of hierarchical data in a table统计表中分层数据的所有子节点
【发布时间】:2011-08-28 23:53:55
【问题描述】:

我想使用邻接模型(父子键)计算表中维护的任何级别的树结构下的所有子节点的数量。表结构和数据如下所示:

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
        • J
    • F
      • K

现在如果你想计算“B 的所有子节点”,我的答案应该是 6。

任何基于纯 SQL 查询的解决方案都会有很大帮助。或者 mysql/php 也可以。

谢谢!

【问题讨论】:

  • 有许多不同的方法可以做到这一点,我已将其发布为stackoverflow.com/questions/5995823/… 的答案。为了确定这些方法中的哪一种是合适的,我们需要知道您希望从该表中获得什么样的信息,以及该表的更新频率——添加和删除信息的频率,以及应该怎样做如果从层次结构的中间删除某些东西,就会发生这种情况。你能否详细说明你想用这个层次结构做什么?
  • 这在SQL平台上已经够简单了,解决方案使用递归。但是对于像你这样的 NONsql,以及没有递归的平台,你必须使用过程和临时表。
  • 我有一个使用 php 和 MySql 的解决方案,请查看我的response。我使用一个查询获得树结构,并实现两个递归函数来计算树中每个节点的所有子节点(分层数据结构)。

标签: php mysql hierarchy sql


【解决方案1】:

您存储数据的方式不允许通过简单的查询来获取总的孩子数。但是看看:

http://en.wikipedia.org/wiki/Nested_set_model

这样的查询在哪里是可能的。

【讨论】:

【解决方案2】:

下面是一个基于 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'

*_num_rows*_fetch_array 替换为您正在使用的SQL 扩展的任何函数。这不会像纯 SQL 解决方案那样有效,但它会起作用。我在函数中查询的方式是假设绑定了参数,但你可以随意执行查询。

【讨论】:

  • 根据表的大小和分支的深度,检索整个表并在内存中进行遍历/计数可能会更有效,而不是发出多个选择语句(也可能反过来是真的)。​​
【解决方案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);

您可以轻松地调整此示例以满足您的要求。

希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    相关资源
    最近更新 更多