Count all child nodes of hierarchical data in a table

前端 未结 3 1294
失恋的感觉
失恋的感觉 2020-12-06 14:02

I want to count number of all child nodes under any level of tree structure maintained in a table using adjacency model (parent-child key). Table structure and data looks l

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 14:34

    Below is a PHP based solution:

    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'
    

    Replace *_num_rows and *_fetch_array with whatever functions for the SQL extension you are using. This won't be as efficient as a pure SQL solution, but it will work. The way I'm querying in the function is assuming bound parameters, but execute the query as you like.

提交回复
热议问题