mysql左连接重复我的表行 - 为什么?

时间:2011-05-29 12:35:10

标签: mysql sql

我有两张桌子:

  • 表1 => product_id,product_quantity =>我这里有25排。
  • 表2 => 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'

此查询使用table1复制table2行。此查询中是否有错误?

首先,我要对product_quantity table1中的所有product_id = '$this'求和,并order_quantity table2中的所有product_hashid = '$this'求和{和} { a - b)显示最终结果。

3 个答案:

答案 0 :(得分:2)

你想要做的事情很好,但不是你实施的。

  
      
  • 我想对product_quantity table1的所有product_id = '$this'求和order_quantitytable2 product_hashid = '$this'所有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; 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; b)显示最终结果。
  •   

一次建立一步。

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;

您可能会发现代码对齐强​​调了产品ID列的不一致列命名。


在更一般的情况下:

{{1}}

有时您需要使用LEFT OUTER JOIN;大多数情况下,你没有。写这个SQL,假设你没有,直到你确定你这样做。

鉴于数据基数(行数),您可能需要在此处执行LOJ。您需要为Table1中列出的那些未列在表2中的产品的订单数量制造零。

{{1}}

答案 1 :(得分:1)

LEFT JOIN将在每种情况下返回所有table1。 http://www.w3schools.com/sql/sql_join_left.asp

如果它们出现在表2中,您真的只想要table1中的产品吗?如果是这样,你只需要JOIN(或INNER JOIN) http://www.w3schools.com/sql/sql_join_inner.asp

答案 2 :(得分:0)

我认为问题是你的JOIN和你的WHERE子句。在此设置中,您将返回table2中的所有数据,这将给您带来麻烦。你的WHERE子句正在查看table1并限制那里的行,但你的JOIN返回table2中的所有行,只返回table1中相等的那些行。

底线:将您的联接更改为INNER JOIN,您的问题将会消失。

相关问题