1

Table Person has columns id and parent_id.

I need get a table with columns id and children_count. How can it be performed? Why I can not write something like this? :

SELECT 
    id, count(parent_id) AS children_count
FROM 
    Person
GROUP BY 
    parent_id;
4

2 回答 2

3

您应该将表外部连接到自身以查找所有 id 及其子项,然后计算计数。

select a.id parent,
       count(b.id) count_child
  from person a left outer join person b
    on a.id = b.parent_id
 group by a.id
 order by a.id;

sqlfiddle演示。

使用右外连接也可以达到相同的结果。

select b.id parent,
       count(a.id) count_child
  from person a right outer join person b
    on a.parent_id = b.id
 group by b.id
 order by b.id; 
于 2013-10-08T05:42:31.997 回答
0

似乎查询的 Select 部分是问题所在。下面将为您提供每个 parent_id 的孩子数

SELECT parent_id, count(id) AS children_count 
FROM Person 
GROUP BY parent_id
于 2013-10-07T22:11:18.590 回答