我在mySQL数据库上有3个表。 产品,库存入库,库存出库。我想按 product_id 对每种产品的库存量和缺货量进行总计。
我在下面使用此查询。但这给了我一些错误的答案。
SELECT product.Product_Name, SUM(stock_in.StockInQuantity) as stockin, S
SUM(stock_out.Quantity) as stockout
FROM product, stock_in, stock_out
WHERE stock_in.Product_ID=product.Product_ID
and stock_out.Product_ID=product.Product_ID
GROUP BY product.Product_ID**
但是,如果我对stockin
和stockout
使用单独的查询,则结果是正确的。
SELECT Product_Name, SUM(StockInQuantity) as stockin
FROM product, stock_in
WHERE stock_in.Product_ID=product.Product_ID
GROUP BY product.Product_ID
SELECT Product_Name, SUM(Quantity) as stockout
FROM product, stock_out
WHERE stock_out.Product_ID=product.Product_ID
GROUP BY product.Product_ID**
因此,请给我一个解决方案,以在一个查询中查找结果或在一个表中回显两个查询结果的结果。
答案 0 :(得分:0)
您可以尝试以下查询:
SELECT p.product_name AS Product_Name,
COALESCE(SUM(si.stockin), 0) AS total_stockin,
COALESCE(SUM(so.stockout), 0) AS total_stockout,
FROM product p
LEFT JOIN (SELECT Product_ID, SUM(StockInQuantity) AS stockin
FROM stock_in
GROUP BY Product_ID) si ON si.Product_ID = p.Product_ID
LEFT JOIN (SELECT Product_ID, SUM(Quantity) AS stockout
FROM stock_out
GROUP BY Product_ID) so ON so.Product_ID = p.Product_ID
GROUP BY Product_Name