I need to return my categories with the item quantity in each department, the parent categories must inherit from the child categories the quantity of products in each category.
Categories
+-------------+----------------------+--------+ | id | name | parent_id | +-------------+----------------------+--------+ | 1 | ELECTRONICS | NULL | | 2 | TELEVISIONS | 1 | | 3 | TUBE | 2 | | 4 | LCD | 2 | | 5 | PLASMA | 2 | | 6 | PORTABLE ELECTRONICS | 1 | | 7 | MP3 PLAYERS | 6 | | 8 | FLASH | 7 | | 9 | CD PLAYERS | 6 | | 10 | 2 WAY RADIOS | 6 | +-------------+----------------------+--------+
Product
+-------------+----------------------+--------+ | id | product | category_id | +-------------+----------------------+--------+ | 1 | TV LCD 32" | 4 | | 2 | TV LCD 45" | 4 | | 3 | TV TUBE 29" | 3 | | 3 | IPOD | 7 | +-------------+----------------------+--------+
Expected result
+-------------+----------------------+------------+ | id | name | level| quantity | +-------------+----------------------+------------+ | 1 | ELECTRONICS | 1 | 4 | | 2 | TELEVISIONS | 2 | 3 | | 3 | TUBE | 3 | 1 | | 4 | LCD | 3 | 2 | | 5 | PORTABLE ELECTRONICS | 2 | 1 | | 6 | MP3 PLAYERS | 3 | 1 | +-------------+----------------------+------------+
I need to do using with recursive, because the speed is much higher than using nested
WITH RECURSIVE category_path (id, name, level, parent_id) AS
(
SELECT id, name, 1 level, parent_id
FROM categories
WHERE parent_id IS NULL
UNION ALL
SELECT c.id, c.name, level + 1, c.parent_id
FROM category_path AS cp
JOIN categories AS c
ON cp.id = c.parent_id
)
SELECT * FROM category_path
Time: 0.020s
using nested
SELECT
parent.id,
parent.name,
parent.parent_id,
COUNT(departaments.product_id)
FROM
categories AS node
INNER JOIN
categories AS parent
ON node.lft BETWEEN parent.lft AND parent.rgt
INNER JOIN
departaments
ON node.id = departaments.categorie_id
GROUP BY
parent.id
ORDER BY
node.lft;
Time: 1.510s