开发者

MySQL multiple left join group by

开发者 https://www.devze.com 2023-04-01 05:53 出处:网络
There is something wrong with this MySQL code. it seems to be returning more stock then there should be.

There is something wrong with this MySQL code. it seems to be returning more stock then there should be.

table positions holds the stock available (multiple positions one product) table orderbody holds the orders ordered products (1 orderheader to many orderbody)

SELECT PRO.ProductID, 
       PRO.ProductCode, 
       SUM( POS.Qty ) AS instock, 
       SUM( OB.Qty ) AS onorder
FROM products AS PRO
LEFT JOIN position AS POS ON POS.ProductID = PRO.ProductID
LEFT JOIN orderbody AS OB ON OB.ProductID = PRO.ProductID
WHERE POS.ProductID = OB.ProductID
GROUP BY PRO.ProductID, POS.ProductID, OB.ProductID
  • i'm getting instock 320
  • actual stock quantity = 40
  • number of 开发者_StackOverflow社区positions = 2 (qty 20 each)

  • onorder = 16 qty

  • actual number of orderbody = 8 rows
  • actually on order = 8 (each with qty = 1)

this is on one of the products

i know it has something to do with the group by but i cant work it out.

Appreciate any help received.


I had the same problem a few days ago. Try it by SELECTing from a separate query: SELECT ... FROM products, (SELECT...)..." where you have the two tables to be left joined. try to test the sub-query by itself first, and try to put it together once ot works. (once you have the data you want, and not duplicates, because that is you problem.


you are selecting this field PRO.ProductCode, but not grouping by it, at a guess it might be the problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消