简体   繁体   English

Mysql LEFT JOIN与可选关系parent <-> child表结合使用不起作用

[英]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 总之我们有

  1. table child products: catalog 表子产品:目录
  2. table parent relations - if it exists! 表父关系-如果存在! contains parent child relations : catalog_product_relation 包含父子关系:catalog_product_relation
  3. table warehouses : warehouses 表仓库:仓库
  4. table products and stock : wh_products 餐桌产品和库存:wh_products

and we are trying to get the stock total qty, where 我们试图获得库存的总数量

  • stock is stored by child products and needs to be summed per that 库存是由子产品存储的,需要按照
  • if a parent relation exists then we should group by and show that data 如果存在父关系,那么我们应该分组并显示该数据

even simpler 更简单

  • for products without a parent: just sum qty (already works) 对于没有父母的产品:数量总和(已经生效)
  • for products with a parent: then rollup and sum by the parent identifier 对于具有父项的产品:然后按父项标识符进行汇总和求和
  • and preferably also get the data for the parent identifier from the catalog (ie the right name and sku) 并且最好还从目录中获取父标识的数据(即正确的名称和sku)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM