MySQL - Returning a list and count of 'sub list'?

Hi Folks,

Firstly, my apologies for the poor title of this question - I went through several ways of phrasing it and none of them were any better!

I have a very simple DB Table, as follows;

ID (INT)
Cat_Name (VAR)
Cat_Shortname (VAR)
SubcategoryOf (INT)

My Query at the moment looks like this;

SELECT *
FROM categories
WHERE SubcategoryOf=0
ORDER BY Cat_Name ASC

The '0' basically indicates its a top level category.  As an example dataset, we could have the following;

ID - 1
Cat_Name - iPods
SubcategoryOf - 0

ID - 2
Cat_Name - Classic
SubcategoryOf - 1

ID - 3
Cat_Name - Touch
SubcategoryOf - 1

That data would basically indicate we have one top level category (iPods) which has 2 subcategories (Classic & Touch).

Now, my current query uses a where clause to only return the top level categories, however I would also like to return a count of the number of sub categories for each row too.

I know how to accomplish this using a left join (if the data was in a different table), but I'm not sure if its possible to do when the data is all in a single table?
RedBullLeeAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

rushShahCommented:
hi try this query..

SELECT *, (SELECT Count(c1.ID) FROM categories c1 WHERE c1.SubCategoryOf=c.ID) AS  'SubCount'
FROM categories c
WHERE SubcategoryOf=0
ORDER BY Cat_Name ASC

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
RedBullLeeAuthor Commented:
Apologies for the delay replying, rushShah.

That has worked perfectly, thank you!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.