views:

43

answers:

2

I would really appreciate some help with my problem:

I have 2 MySQL tables, categories and posts, laid out (simplified) like so:

categories:

CATID - name - parent_id

posts:

PID - name - category

What I would like to do is get the total amount of posts for each category, including any posts in subcategories.

Right now I am getting the total number of posts in each (top-level) category (but not subcategories) by doing:

"SELECT c.*, COUNT(p.PID) as postCount 
        FROM categories AS c LEFT JOIN posts AS p 
        ON (c.CATID = p.category) 
        WHERE c.parent='0' GROUP BY c.CATID ORDER BY c.name ASC";

The question once again is, how can I get the sum totals for each category including the totals for each related subcategory?

Restructuring the database to a nested set format is not possible, as I am maintaining an existing system.

Thanks for your help!

A: 

I think you want to look at the Rollup operator. I believe this will get you what you want.

http://msdn.microsoft.com/en-us/library/ms189305%28SQL.90%29.aspx

Randy

Randy Minder
An MSDN link for a MySQL question?
Andomar
+1  A: 

If the categories are not nested infinitely, you can JOIN them one level at a time. Here's an example for up to 3 levels of nesting:

SELECT c.name, COUNT(DISTINCT p.PID) as postCount 
FROM categories AS c 
LEFT JOIN categories AS c2
    ON c2.parent = c.catid
LEFT JOIN categories AS c3
    ON c3.parent = c2.catid
LEFT JOIN posts AS p 
    ON c.CATID = p.category
    OR c2.CATID = p.category
    OR c3.CATID = p.category
WHERE c.parent = '0' 
GROUP BY c.CATID, c.name
ORDER BY c.name ASC
Andomar
Thanks for the quick response! Good solution.I couldn't wait and already fixed it in a more cumbersome way though :D, next time I will use your solution however.
Partizan