M
M
muhasa2017-10-19 09:18:09
MySQL
muhasa, 2017-10-19 09:18:09

How to select all categories with products with additional conditions?

Hello.
There are two tables
groups
id | id_parent | name
products
id | id_group | name
The task is to write a query that will return all groups with the number of goods in this group.
For example,
groups.id | groups.id_parent | name | product_count
1 | 0 | dvd player | 10
Extras conditions:
1) If there are no goods in the group, then the group must also be included in the resulting selection with the number of goods equal to zero.
2) All groups, regardless of their position in the hierarchy, can have their own products. You need to return exactly the amount that corresponds to a specific group, but not to subgroups of this group.
How I tried to do:

SELECT g.id id, g.id_parent id_parent, g.name as 'name', count( p.id_group ) product_count 
FROM groups g LEFT JOIN products p ON g.id = p.id_group 
GROUP BY p.id_group

However, this request does not work correctly. Why - has not yet figured out.
I ask the respected community to help deal with this request.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question