我的SQL查询有问题。当我使用多个JOIN时,结果是错误的。
SELECT name, stock,SUM(order_items.qty),
SUM(shipping_items.qty) FROM shipping_items
JOIN mnm_products
ON mnm_products.id = shipping_items.product_id
JOIN order_items
ON mnm_products.id = order_items.product_id
GROUP BY mnm_products.id
当我只使用
时SELECT name, stock,
SUM(shipping_items.qty) FROM shipping_items
JOIN mnm_products
ON mnm_products.id = shipping_items.product_id
GROUP BY mnm_products.id
是对的。但是当我使用2个连接时。两者的结果是一样的。 有人可以帮助我吗?
答案 0 :(得分:0)
相关子查询可能最好:
select p.*,
(select sum(si.qty)
from shipping_items si
where si.product_id = p.id
) as shipping_items,
(select sum(oi.qty)
from order_items oi
where oi.product_id = p.id
) as order_items
from mnm_products p;