在mysql中获取最畅销产品的当前库存

时间:2018-08-14 09:33:00

标签: php mysql

我想从数据库中获取最畅销产品的当前库存。我已经成功获取了最畅销的产品,但无法在同一查询中获取其当前库存。

SELECT product_name, product_code, SUM(qty) As TotalQuantity FROM `order_items` GROUP BY product_code ORDER BY SUM(qty) DESC LIMIT 5

库存表类似

enter image description here

如果您需要更多信息,我会更新问题。

1 个答案:

答案 0 :(得分:1)

假定表的名称为inventory。我使用相关子查询来获取当前库存值

SELECT oi.product_name, oi.product_code,
SUM(oi.qty) AS TotalQuantity,
(SELECT SUM(inv.qty) FROM `inventory` AS inv WHERE inv.product_code = oi.product_code) AS CurrentStock
FROM `order_items` AS oi
GROUP BY oi.product_code
ORDER BY TotalQuantity DESC
LIMIT 5