我有 2 张 table :
- Table1 => Product_id, Product_quantity => 这里有 25 行。
- Table2 => Product_hashid, order_quantity => 这里我有 1 个
查询行。
我构建了这个 mysql 查询:
SELECT SUM(table1.product_quantity) - SUM(order_quantity) AS instocks
FROM table1 -- table.1 in original
LEFT JOIN table2 ON table2.product_hashid = table1.product_id
WHERE table1.product_id = '$thisid'
此查询将 table2 行与 table1 重复。此查询是否有错误?
首先,我想对 table1
中 product_id = '$this'
中的所有 product_quantity
求和,并对所有 order_quantity
求和code> in table2
where product_hashid = '$this'
并 make (a - b) 显示最终结果。
最佳答案
您对自己想做的事情的概述很好,但这不是您实现的。
- I want to sum all
product_quantity
fromtable1
whereproduct_id = '$this'
and sum allorder_quantity
intable2
whereproduct_hashid = '$this'
and make (a - b) to display a final result.
一步一步地构建它。
SELECT SUM(product_quantity) FROM Table1 WHERE Product_ID = '$this';
SELECT SUM(order_quantity) FROM Table2 WHERE Product_HashID = '$this';
SELECT (SELECT SUM(product_quantity) FROM Table1 WHERE Product_ID = '$this') -
(SELECT SUM(order_quantity) FROM Table2 WHERE Product_HashID = '$this')
FROM Dual;
您可能会发现代码对齐强调了产品 ID 列的不一致的列命名。
在更一般的情况下:
SELECT Product_ID, SUM(product_quantity) AS Product_Quantity
FROM Table1
GROUP BY Product_ID;
SELECT Product_HashID AS Product_ID, SUM(order_quantity) AS Order_Quantity
FROM Table2
GROUP BY Product_HashID;
SELECT p.Product_ID, p.Product_Quantity - o.Order_Quantity AS SurplusOnHand
FROM (SELECT Product_ID, SUM(product_quantity) AS Product_Quantity
FROM Table1
GROUP BY Product_ID) AS P
JOIN (SELECT Product_HashID AS Product_ID, SUM(order_quantity) AS Order_Quantity
FROM Table2
GROUP BY Product_HashID) AS O
ON O.Product_ID = P.Product_ID;
有时您需要使用 LEFT OUTER JOIN;大多数情况下,你不知道。假设您不这样做,然后编写 SQL,直到您确信您这样做为止。
鉴于数据基数(行数),您可能需要在此处执行 LOJ。对于表1中列出的、表2中未列出的产品,您需要将订单数量制造为零。
SELECT (SELECT SUM(product_quantity) FROM Table1 WHERE Product_ID = '$this') -
NVL(SELECT SUM(order_quantity) FROM Table2 WHERE Product_HashID = '$this'), 0)
FROM Dual;
SELECT p.Product_ID, p.Product_Quantity - NVL(o.Order_Quantity, 0) AS SurplusOnHand
FROM (SELECT Product_ID, SUM(product_quantity) AS Product_Quantity
FROM Table1
GROUP BY Product_ID) AS P
LEFT OUTER JOIN
(SELECT Product_HashID AS Product_ID, SUM(order_quantity) AS Order_Quantity
FROM Table2
GROUP BY Product_HashID) AS O
ON O.Product_ID = P.Product_ID;
关于mysql left join 重复我的表行 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6167743/