计算MySQL表中的引用行

时间:2011-08-01 15:47:10

标签: mysql

我有一个看起来像这样的表:

Id | Name                    | Parent
---+-------------------------+-------
1  | Parent One              | 0
2  | Child of Parent One     | 1
3  | Parent Two              | 0
4  | Parent Three            | 0
5  | Parent Four             | 0
6  | Child of 1st Parent     | 1
7  | Child of 2nd Parent     | 3
8  | Child of 3nd Parent     | 4

该表不代表层次结构:每个项目都是子项或父项,但不是两者。

我想在它上面运行一个返回此内容的查询:

Id | Name                    | ChildCount
---+-------------------------+-----------
1  | Parent One              | 2
3  | Parent Two              | 1
4  | Parent Three            | 1
5  | Parent Four             | 0

我猜这可能有用,但它并没有:

SELECT parents.id, parents.name, COUNT(parents.id = children.parent) AS childCount
FROM (SELECT * FROM items WHERE parent = 0) parents,
     (SELECT * FROM items WHERE parent > 0) children

我该怎么做?

1 个答案:

答案 0 :(得分:2)

SELECT a.id, a.Name, COUNT(b.id) as ChildCount
FROM table1 a
LEFT JOIN table1 b ON (b.Parent = a.id)
GROUP BY a.id [,a.Name] // ,a.Name is not mandatory for mysql, `GROUP BY a.id` is enough

您可能还想添加WHERE a.Parent = 0以仅显示父行。

已更新COUNT(*)已更改为COUNT(b.id)

对于长子:

SELECT x.id, x.Name, x.ChildCount, c.Name AS eldest_child_name
FROM
(
SELECT a.id, a.Name, COUNT(b.id) as ChildCount, MAX(b.id) as max_child_id
FROM table1 a
LEFT JOIN table1 b ON (b.Parent = a.id)
GROUP BY a.id 
)X
LEFT JOIN table1 c ON (c.id = X.max_child_id)