2011-05-29 44 views
2

我有2個表:mysql左連接重複我的錶行 - 爲什麼?

  • 表1 => 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' 

這個查詢複製表2一行表1。這個查詢中有一些錯誤嗎?

首先,我想從那裏table1總結product_id = '$this'所有product_quantitytable2其中product_hashid = '$this'總結所有order_quantity和使( - B)顯示最終結果。

+0

是不是'FROM table.1'是一個miscopy? – 2011-05-29 12:39:17

回答

0

我認爲問題是你的JOIN和你的WHERE子句。在這個設置中,你將返回table2中的所有數據,這會給你一個混亂。您的WHERE子句正在查看table1並限制這些行,但您的JOIN將返回table2中的所有行,並且只返回table1中相同的所有行。

底線:將您的連接更改爲INNER JOIN,您的問題將消失。

+0

首先我想從table1中總結所有product_quantity,其中product_id ='$ this'並且總結table2中的所有order_quantity,其中product_hashid ='$ this'並且使得(a-b)顯示最終結果 – wyknzo 2011-05-29 13:13:29

+0

@ user764122 - 爲此,只需按照我的建議,並將您的JOIN類型更改爲INNER JOIN即可。這會給你你想要的東西。 – IAmTimCorey 2011-05-29 15:35:41

2

你想要做什麼的輪廓很好,但它不是你實現的。

  • 我想從那裏table1總結product_id = '$this'所有product_quantity,總結所有order_quantitytable2其中product_hashid = '$this',使(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中列出的未列在表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;