Shaun,
I don't use LEFT JOIN if I can help it :queasy: ... seems confusing to me and you can do exactly the same in the WHERE clause using AND, if necessary.
Anyway, I think you're going to have to get clear in your mind (and ours!) exactly what you want to count. 😉
Try simplifying the situation into exactly the 'nub' of the problem.
For example, suppose we have categories like this ...
Records:
+--------+-----------+------------+
| cat_id | cat_title | cat_sub_of |
+--------+-----------+------------+
| 1 | Dog | [NULL] |
| 2 | Bird | [NULL] |
| 3 | Eagle | 2 |
| 4 | Alsation | 1 |
| 5 | Terrier | 1 |
| 6 | Hawk | 2 |
| 7 | Dove | 2 |
+--------+-----------+------------+
There are two ways to look at this ...
1) List each main category item and find out which subcategory it belongs to:
SELECT main.cat_title as main_cat_title, main.cat_id as main_cat_id
, sub.cat_title AS sub_cat_title, sub.cat_id AS sub_cat_id
FROM categories as main, categories as sub
WHERE main.cat_sub_of = sub.cat_id
ORDER BY main.cat_id ASC
Note that, in this scheme, each main cat_id has one and only one subcategory, so no point in using COUNT and GROUP BY!
Results:
+----------------+-------------+---------------+------------+
| main_cat_title | main_cat_id | sub_cat_title | sub_cat_id |
+----------------+-------------+---------------+------------+
| Eagle | 3 | Bird | 2 |
| Alsation | 4 | Dog | 1 |
| Terrier | 5 | Dog | 1 |
| Hawk | 6 | Bird | 2 |
| Dove | 7 | Bird | 2 |
+----------------+-------------+---------------+------------+
... or ...
2) List the subcategories, and find out which main categories they refer to ...
SELECT sub.cat_title AS sub_cat_title, sub.cat_id as sub_cat_id
, main.cat_title as main_cat_title, main.cat_id as main_cat_id
FROM categories as main, categories as sub
WHERE main.cat_sub_of = sub.cat_id
ORDER BY sub.cat_title ASC, main_cat_title ASC
Results:
+---------------+------------+----------------+-------------+
| sub_cat_title | sub_cat_id | main_cat_title | main_cat_id |
+---------------+------------+----------------+-------------+
| Bird | 2 | Dove | 7 |
| Bird | 2 | Eagle | 3 |
| Bird | 2 | Hawk | 6 |
| Dog | 1 | Alsation | 4 |
| Dog | 1 | Terrier | 5 |
+---------------+------------+----------------+-------------+
Now it's possible to get a count on the above, to find out how many main categories are in each subcategory ...
SELECT sub.cat_title AS sub_cat_title, sub.cat_id as sub_cat_id
, COUNT(main.cat_id) as main_cat_count
FROM categories as main, categories as sub
WHERE main.cat_sub_of = sub.cat_id
GROUP BY sub.cat_title
ORDER BY sub.cat_title ASC
... and you'd get ...
Results:
+---------------+------------+----------------+
| sub_cat_title | sub_cat_id | main_cat_count |
+---------------+------------+----------------+
| Bird | 2 | 3 |
| Dog | 1 | 2 |
+---------------+------------+----------------+
... as expected.
I hope that helps to clarify things. See how you get on!
Paul 🙂