[英]Mysql LEFT JOIN in combination with optional relation parent<->child table not working
I am having some troubles when combining left joins with optional values to group by. 将左联接与可选值分组时遇到麻烦。
In short we have 总之我们有
and we are trying to get the stock total qty, where 我们试图获得库存的总数量
even simpler 更简单
I hope it is clear ... the query below is not working. 我希望很清楚...下面的查询不起作用。 Step 1 to me looked like just getting the parent ID in a column
对我来说,步骤1看起来像只是在列中获取父ID
and step 2 is to sum the qty's for simple products per simple product and for parent products sum it up for all child simple product but show the parent data 第2步是将每个简单产品的简单产品的数量求和,对于父产品,将所有子简单产品的数量求和,但显示父数据
select c.sku as sku,
IFNULL(pr.parent_id, c.entity_id) as main_id,
c.type_id as type,
SUM(CASE WHEN (wh.code='LR') THEN FLOOR(wp.qty) ELSE 0 END) AS 'Loc1',
SUM(CASE WHEN (wh.code='LS') THEN FLOOR(wp.qty) ELSE 0 END) AS 'Loc2'
FROM catalog c,
wh_products wp,
warehouses wh
LEFT JOIN catalog_product_relation pr ON pr.parent_id = c.entity_id
WHERE c.entity_id = wp.product_id and wp.warehouse_id = wh.warehouse_id and wp.qty > 0
GROUP BY main_id
I would start by writing the JOIN
s correctly and aggregating by the columns in the SELECT
: 我将从正确地编写
JOIN
并按SELECT
的列开始汇总:
SELECT c.sku as sku,
COALESCE(pr.parent_id, c.entity_id) as main_id, c.type_id as type,
SUM(CASE WHEN wh.code = 'LR' THEN FLOOR(wp.qty) ELSE 0 END) AS Loc1,
SUM(CASE WHEN wh.code = 'LS' THEN FLOOR(wp.qty) ELSE 0 END) AS Loc2
FROM catalog c LEFT JOIN
wh_products wp
ON c.entity_id = wp.product_id LEFT JOIN
warehouses wh
ON wp.warehouse_id = wh.warehouse_id AND wp.qty > 0 LEFT JOIN
catalog_product_relation pr
ON pr.parent_id = c.entity_id
GROUP BY c.sku, COALESCE(pr.parent_id, c.entity_id), c.type_id;
I'm not sure if this fixes your problems. 我不确定这是否可以解决您的问题。 Without sample data and desired results, it is a bit hard to follow the logic.
没有样本数据和理想的结果,很难遵循逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.