gpt4 book ai didi

mysql - 如何使用mysql计算库存

转载 作者:搜寻专家 更新时间:2023-10-30 22:26:37 25 4
gpt4 key购买 nike

我正在寻找一种从两个表计算库存数量的方法。

我的表记录如下:

下面是我的产品表

enter image description here

我有两个表,第一个是“stockinward”,用于购买库存,另一个是 stockoutward,用于出售库存。

下图为入库表截图

enter image description here

这是 stockoutward 的截图

enter image description here

下面是我计算库存的查询

SELECT 
p.Id,
p.Name,
p.UnitPrice,
((SELECT
IFNULL(SUM(Quantity), 0)
FROM
stockinward
WHERE
ProductId = p.Id) - (SELECT
IFNULL(SUM(Quantity), 0)
FROM
stockoutward
WHERE
ProductId = p.Id)) AS Quantity

来自 产品p;

enter image description here

但问题出在上面的查询中,当我有超过 1000 种产品时,它需要超过 8 秒,那么有没有其他方法可以在 1 或 2 秒内得到相同的结果?

提前致谢:)

最佳答案

你也可以使用连接而不是子查询

SELECT 
p.Id,
p.Name,
p.UnitPrice,
IFNULL(qin.Quantity, 0) - IFNULL(qout.Quantity, 0) AS Quantity
FROM product
LEFT JOIN (
SELECT ProductId, SUM(Quantity) AS Quantity
FROM stockinward
GROUP BY ProductId
) qin ON p.Id = qin.ProductId
LEFT JOIN (
SELECT ProductId, SUM(Quantity) AS Quantity
FROM stockoutward
GROUP BY ProductId
) qout ON p.Id = qout.ProductId

关于mysql - 如何使用mysql计算库存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50617235/

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