Reputation: 97641
I have a table that looks like this:
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
The table does not represent a hierarchy: Every item is either a child or a parent, but not both.
I'd like to run a query on it that returns this:
Id | Name | ChildCount
---+-------------------------+-----------
1 | Parent One | 2
3 | Parent Two | 1
4 | Parent Three | 1
5 | Parent Four | 0
I guessed that this might work, but it didn't:
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
How should I be doing this?
Upvotes: 2
Views: 74
Reputation: 37382
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
You may also want to add WHERE a.Parent = 0
to show only parent rows.
Updated (COUNT(*)
changed to COUNT(b.id)
)
For Eldest Child:
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)
Upvotes: 2