Structure of the Category table:
- id
- title
- parent_id
Structure of the Item table:
- id
- title
- is_active (0 или 1)
- category_id
Tables are associated with the category_id field by a one-to-many relationship. Those. 1 category can have many items.
The two-level hierarchy in the Category table. This defines the main categories and subcategories. Categories are those records in which parent_id = NULL. And subcategories, these are those records in which parent_id = to some id.
One Item can belong to both the main category (where parent_id = null) and the subcategory (child). Item can be active and not active (0 or 1).
You need to make a query and select from the Category table all the main categories (which have parent_id = null) that have active items (is_active = 1) and which have subcategories also with active itemes. i.e If the child subcategory has items with is_active = 0, then do not display this category.
I could only choose the main categories in which only active items:
SELECT categories.title, count(analyses.id) FROM items
INNER JOIN categories on items.category_id = categories.id
WHERE categories.parent_id IS NULL
AND categories.is_active = 1
GROUP BY analyses.category_id
ORDER BY analyses_categories.title
But with subcategories can not cope anymore, tell me please who has more experience.
join
andexists
. – sgeddes