我有3张桌子
Products
[id, name]
Purchases
[id, product_id, quantity, date]
Sales
[id, product_id, quantity, date]
我想列出每种产品的剩余数量的所有产品。
我已尝试使用以下查询,但它无效。
SELECT pr.id, pr.name, (sum(pu.quantity))-sum(s.quantity) as quantity
FROM `products` pr
join purchase pu ON pu.product_id = pr.id
left join sales s ON s.product_id = pr.id
GROUP BY pr.id
我知道上面的查询会为purchase
和sales
创建重复的行,因为我们将这两个表与产品一起加入。
请帮我写出正确的查询以查找剩余的产品数量
答案 0 :(得分:1)
您需要在join
之前汇总。一种方法明确在from
子句中:
SELECT pr.id, pr.name,
(coalesce(pu.sumq, 0) - coalesce(s.sumq, 0)) as quantity
FROM `products` pr left join
(SELECT pu.product_id, SUM(pu.quantity) as sumq
FROM purchase pu
GROUP BY pu.product_id
) pu
ON pu.product_id = pr.id left join
(SELECT s.product_id, SUM(s.quantity) as sumq
FROM sales s
GROUP BY s.product_id
) s
ON s.product_id = pr.id
GROUP BY pr.id, pr.name;
答案 1 :(得分:0)
请改用IFNULL
。因为 12 + null = null
SELECT pr.id, pr.name,
sum(ifnull(pu.quantity,0))-sum(ifnull(s.quantity,0)) as quantity
FROM `products` pr
left join purchase pu ON pu.product_id = pr.id
left join sales s ON s.product_id = pr.id
GROUP BY pr.id,pr.name
由于您在结果集中添加了pr.name
,因此您还需要将其放在GROUP BY
子句中。