如何计算父类别及其后代中的项目


How to count items in parent category and its descendants?

我有两个表:类别和对象。类别可以有一个或多个子项。 这些孩子可以有自己的孩子。 因此,层次结构是无限的。 一个孩子只能有一个父母。 父类别是parent_id为 NULL 的类别。 类别具有对象(一对多关系)。

示例数据:

类别表

id   name       parent_id    
1    Sports     NULL
2    Home       NULL
3    Fashion    NULL
4    Cycling    1
5    Football   1
6    Bath       2
7    Bedroom    2
8    Lighting   7

假设类别中的对象数如下所示:

name       COUNT(object)   
Sports     5
Home       3
Fashion    4
Cycling    2
Football   3
Bath       2
Bedroom    1
Lighting   3

我只需要获取父类别的对象计数,包括使用纯 MySql 或 MySql 和 PHP 的后代中的对象计数。

这是我正在寻找的结果。

Sports     5 + 2(for Cycling)+3(for Football) = 10
Home       3+2(Bath)+1(Bedroom)+3(Lighting)= 9
Fashion    4

我知道嵌套集,但无法更改当前的数据库结构。

下面的php代码可以解决这个问题,也许有更好的答案,但是我现在告诉的

<?php
try{
    $conn = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');
    $stm = $conn->prepare('select tem.id, tem.num, c.name, c.parent_id from category c inner join (SELECT c.id ,count(c.id) as num FROM `category` c left join object o on o.category = c.id 
group by c.id) tem on c.id = tem.id');
    $stm->execute();
    $result = $stm->fetchAll(PDO::FETCH_OBJ);
    $temp = array();
    foreach($result as $row){
        $temp[$row->id] = $row;
    }

    $pre_final = moh($temp);
    $final = array();
    foreach ($pre_final as $row){
            if(!$row->parent_id){
                $final[] = $row;
            }
    }
    print_r($final);
}
catch(PDOException $e){
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
function moh($arr){
    $flag = true;
    foreach($arr as $row){
        if(!$row->parent_id){
        } else{
            $arr[$row->parent_id]->num += $row->num; 
            $row->num = 0;
        }
    }

    foreach($arr as $row){
        if(!$row->parent_id){
        } else{
            if($row->num != 0){
                $flag = false;
                break;
            }
        }
    }
    if($flag){
        return $arr;
    } else{
        return moh($arr);
    }

}