简体   繁体   中英

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
  3. table warehouses : warehouses
  4. table products and stock : 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)

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

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

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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