I have got 2 tables: categories
and products
.
Categories have parent-child relationship structure and the data is fetched by joining the same table.
When fetching the data, I have to count:
- how many products each category contains which have
stock >= 1
- how many subcategories a category contains which contain at least 1 product with
stock >= 1
SELECT c. * , count( DISTINCT s.cat_id ) AS number_of_subcategories, count( DISTINCT p.id ) AS number_of_products FROM categories c
LEFT JOIN categories s
ON s.parent_id = c.cat_id
LEFT JOIN products p
ON p.cat_id = c.cat_id AND p.stock >= 1
GROUP BY c.cat_name
ORDER BY number_of_products ASC
At the first glance all goes well, but unfortunately I get total number of all subcategories.
Do I miss one more join or what is my problem so far?
Here is the code: SQLFiddle