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?
You may also want to add
WHERE a.Parent = 0to show only parent rows.Updated (
COUNT(*)changed toCOUNT(b.id))For Eldest Child: