gpt4 book ai didi

MYSQL SUM 数量与连接

转载 作者:行者123 更新时间:2023-11-29 21:32:19 25 4
gpt4 key购买 nike

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

最佳答案

您可能最好使用相关子查询:

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;

关于MYSQL SUM 数量与连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35156756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com