Answer the question
In order to leave comments, you need to log in
Counting the number of items in categories and subcategories (SQL)?
There was a problem with counting the number of items in categories and subcategories. Each category has subcategories, and subcategories have their own subcategories. The number of such levels is unlimited. Records are stored in the "bottom" category. Categories and records are represented as separate tables in the database.
The table structure is something like this:
Categories
-------------
id
parent_id
....
Posts
-------------
id
....
category_id
.....
SELECT categories.*,(SELECT COUNT(posts.id) FROM posts WHERE posts.category_id = categories.id) AS count FROM categories WHERE 1
Answer the question
In order to leave comments, you need to log in
Hello.
Yes, sir. What if it's like this? The request has not been tested. Just like an idea. On a whim...
SELECT par.Id, COUNT(po.id) AS postCount
FROM Categories AS par
INNER JOIN Categories AS sub ON par.id = sub.parent_id
INNER JOIN Posts AS po ON po.id = sub.id
GROUP BY par.Id
Dig towards nested sets for the category table. Then everything will be much easier.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question