Select all categories with COUNT of sub-categories

Viewed 664

I need to select all categories with count of its sub-categories.

Assume here are my tables:

categories

id | title
----------
1  | colors
2  | animals
3  | plants

sub_categories

id | category_id | title | confirmed
------------------------------------
1        1          red       1
2        1          blue      1
3        1          pink      1
4        2          cat       1
5        2          tiger     0
6        2          lion      0

What I want is :

id |  title  | count
------------------
1    colors     3
2    animals    1
3    plants     0

What I have tried so far:

SELECT c.id, c.title, count(s.category_id) as count from categories c
LEFT JOIN sub_categories s on c.id = s.category_id
WHERE c.confirmed = 't' AND s.confirmed='t'
GROUP BY c.id, c.title
ORDER BY count DESC

The only problem with this query is that this query does not show categories with 0 sub categories!

You also can check that on SqlFiddle

Any help would be great appreciated.

2 Answers
Related