用名称替换id形成现有查询中的另一个表

时间:2016-04-22 20:18:24

标签: mysql sql join

这是我获取每个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;

1 个答案:

答案 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)