这是我获取每个Product_Id
剩余股票的查询。但是,我不确定如何从Product_Name
表中添加Product
。我只想将i.Product_Id
替换为p.Product_Name
,其中p是Product的别名。我知道Product p
应插入FROM
但不确定如何将其与给定查询相关联。
顺便说一句,Product.Id = Inventory.Product_Id
SELECT
i.Product_Id,
i.Stocks,
s.Sales,
i.Stocks - s.Sales AS Remaining
FROM (SELECT product_id, COALESCE(SUM(quantity),0) AS Stocks FROM inventory GROUP BY product_id) i
LEFT JOIN (SELECT product_id, COALESCE(SUM(quantity),0) AS Sales FROM sales_detail GROUP BY product_id ) s
USING(product_id);
先谢谢你们!
UPDATE !!
以下查询是我更新过的,有人可以检查我是否将产品与现有的JOIN USING
正确关联,谢谢!
SELECT
i.Product_Id,
p.Product_Name,
i.Stocks,
s.Sales,
i.Stocks - s.Sales AS Remaining
FROM (SELECT product_id, COALESCE(SUM(quantity),0) AS Stocks FROM inventory GROUP BY product_id) i
LEFT JOIN (SELECT product_id, COALESCE(SUM(quantity),0) AS Sales FROM sales_detail GROUP BY product_id ) s
USING(product_id)
JOIN Product p
ON i.Product_Id=p.Id;
答案 0 :(得分:1)
您需要使用JOIN
表格Products
。
SELECT
p.Product_Name,
i.Stocks,
s.Sales,
i.Stocks - s.Sales AS Remaining
FROM (SELECT product_id, COALESCE(SUM(quantity),0) AS Stocks FROM inventory GROUP BY product_id) i
JOIN Products AS p USING (product_id)
LEFT JOIN (SELECT product_id, COALESCE(SUM(quantity),0) AS Sales FROM sales_detail GROUP BY product_id ) s
USING(product_id)