The following query can be used to get the amount of stock alerts set for all products:
SELECT `product_id`, COUNT(`alert_stock_id`) AS `qty_alert`
FROM `product_alert_stock`
GROUP BY `product_id`
For configurable products (a product which has child products), how can I get the sum of its child products as well as its own in one query?
So if a product has children in catalog_product_super_link
, the count of all the product_id
should be retrieved from product_alert_stock
and added to that parent product its count.
Example data in catalog_product_super_link
+---------+------------+-----------+
| link_id | product_id | parent_id |
+---------+------------+-----------+
| 1 | 2 | 1 |
| 2 | 3 | 1 |
| 3 | 4 | 1 |
+---------+------------+-----------+
Example result set of the query supplied earlier:
- ID 1: 0 stock alerts
- ID 2: 5 stock alerts
- ID 3: 2 stock alerts
- ID 4: 2 stock alerts
The desired result set should be:
+------------+-----------+
| product_id | qty_alert |
+------------+-----------+
| 1 | 9 | # 0 + 5 + 2 + 2
| 2 | 5 |
| 3 | 2 |
| 4 | 2 |
+------------+-----------+
This is probably a simple join or subquery problem, but I can't get it figured out in one query with an unidentified data set (i.e. no product ID filter).
EDIT @ 14-09-2015 // Further clarification
There might not be any results in product_alert_stock
, then qty_alert
is 0.
This query is supposed to be used inside a sub query (JOIN
):
SELECT `e`.`entity_id` as `e_product_id`, `qty_alert` -- [...]
FROM `catalog_product_entity` as `e`
LEFT OUTER JOIN (
-- [...]
-- query to retrieve the alert count als described in question, with `qty_alert` as identifier
) ON `e`.`entity_id` = `xyz`.`product_id`
-- `xyz` being the table holding `product_id` and `qty_alert` values to join
-- [...]
Tried fitting the given answers below into the sub query but it does not yield the correct result set, see the comment below the answers.
PS. If anyone wonders, these tables come from Magento.