MySQL离开连接重复我的表行-为什么?

问题描述

| 我有2张桌子: 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\'
查询与table1复制table2行。这个查询中有错误吗? 首先,我想对来自ѭ3的ѭ2的所有ѭ1求和,并将ѭ6的ѭ5的所有ѭ4求和,并使(a-b)显示最终结果。     

解决方法

        您想做什么的轮廓很好,但不是您实现的轮廓。      我想将ѭ2中的所有ѭ1中的所有ѭ1进行求和,并将ѭ6中的所有ѭ4中的所有ѭ4求和,并使(a-b)显示最终结果。    一次建立一个步骤。
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中未列出的那些产品中的产品的订购数量制造一个零。
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;
    ,        在每种情况下,LEFT JOIN都会返回所有table1。 http://www.w3schools.com/sql/sql_join_left.asp 如果表2中出现产品,您实际上是否只想要表1中的产品?如果是这样,您只需要JOIN(或INNER JOIN) http://www.w3schools.com/sql/sql_join_inner.asp     ,        我认为问题是您的JOIN和WHERE子句。在此设置中,您将从表2中返回所有数据,这将使您一团糟。您的WHERE子句正在查看table1并限制其中的行,但是JOIN返回table2中的所有行,并且仅返回table1中的那些相等的行。 底线:将您的联接更改为“内部联接”,您的问题将消失。