0

我的 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 个连接时。两者的结果是一样的。有人可以帮我吗?

4

1 回答 1

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;
于 2016-02-02T15:06:48.213 回答