I have a table that looks like this:
Categories:
cId | Name | Parent
----+-------------------------+-------
1 | Parent One | NULL
2 | Child of 1st Parent | 1
3 | Parent Two | NULL
4 | Child of 1st Parent | 1
5 | Child of 2nd Parent | 2
The table does not represent a heirarchy: Every item is either a child or a parent, but not both.
And one table like this:
Posts:
pId | Name | cID
----+-------------------------+-------
1 | Post 1 | 1
2 | Post 2 | 2
3 | Post 3 | 2
4 | Post 4 | 3
I’d like to run a query on it that returns this:
cId | Count
---+---------
1 | 3
2 | 2
3 | 1
4 | 0
5 | 0
Count is the number of posts connected to the category.
All categories should be returned.
Parent categories should have the count of the category + child categories sum. (this is one of the things I’m having problem with)
Child categories should have the category sum.
How should I do this?
From your expected results, it looks like you don’t care about grandchildren and lower, in which case, this should work. To get the correct parent count, I’m checking for Parent IS NULL or Count(children) > 0, in which case, I’m adding 1:
Here is some sample fiddle: http://www.sqlfiddle.com/#!2/b899f/1
And the results:
—EDIT—
From reading your comments, it looks like you want something like this:
http://www.sqlfiddle.com/#!2/eb0d2/3