I have h that type table
Now we want full binary tree And full Left and right chides count
Unfortunately, this is not efficiently possible using only SQL (the fact that each node can only have two children, left and right, does not help because the nodes can still be nested arbitrarily deep), you have to do it recursively using PHP:
function countChildren($parentId) {
$children = (`SELECT user_id FROM table where parent_id = ?`, $parentId); // Pseudocode, use a prepared statement with your ORM or MySQL library/PDO
$count = count($children);
foreach($children as $userId) {
$count += countChildren($userId);
}
return $count;
}
However, if you switch your table to use a nested set instead of a tree, querying children for information becomes much more efficient:
SELECT count(*) FROM table AS t JOIN table as parent_table ON (t.left > parent_table.left AND t.right < parent_table.right) WHERE parent_table.user_id = ?;
You will need to keep function in loop then run it , hope this helps you.
Thanks
SELECT leg , count(user_id)as Count FROM table GROUP BY leg
This will show the count of left and right