2013-08-30 56 views
0

我得到一個錯誤:錯誤編號:1242子查詢返回多個1行
我怎樣才能得到DISTINCT/GROUP BY行爲更新詢問

因爲我UPDATE的子查詢產生重複值。我知道DISTINCTGROUP BY可以刪除SELECT查詢中的重複值。我可以如何解決它在UPDATE查詢。我的查詢是這裏

UPDATE 
    product_stock AS S 
LEFT JOIN 
    product_purchase_item AS I 
ON 
    S.product_id=I.product_id AND S.product_size=I.product_size 
LEFT JOIN 
    product_purchases AS P 
ON 
    I.product_purchase_item_id=P.product_purchase_item_id 
SET 
    S.product_size_quantity=S.product_size_quantity+I.quantity 
WHERE 
    S.product_id=? 
AND 
    S.product_size=? 

想,如果我把它轉換在SELECT查詢

SELECT 
S.* 
FROM 
product_stock AS S 
LEFT JOIN 
product_purchase_item AS I 
ON 
S.product_id=I.product_id AND S.product_size=I.product_size 
LEFT JOIN 
product_purchases AS P 
ON 
I.product_purchase_item_id=P.product_purchase_item_id 

查詢返回

 
product_stock_id product_id product_size product_quantity 

10     216   1   1 
10     216   1   1 
11     216   5   1 

但我需要(就在DISTINCT關鍵字可以在SELECT做到這一點查詢)

 
product_stock_id product_id product_size product_quantity 

10     216   1   1 
11     216   5   1 

但是,我如何檢索像上面的數據(獨特的價值)在我的UPDATE子查詢?是否有可能使用DISTINCT關鍵字或像我的UPDATE查詢中的任何內容?

回答

0

這應該做的伎倆。是否有包含product_purchases表的原因,因爲它在查詢中似乎是多餘的?

UPDATE product_stock SET product_size_quantity = product_size_quantity + I.quantity 

from product_stock 
INNER JOIN (select product_id, product_size, sum(quantity) from product_purchase_item group by product_id, product_size) AS I 
ON product_stock.product_id=I.product_id AND product_stock.product_size=I.product_size 

WHERE product_stock.product_id=? 
AND product_stock.product_size=? 
+0

是的,我正在使用'AFTER INSERT ON' product_purchases'trigger'。所以我需要product_purchases表。在這裏我的[change_stock_when_purchases TRIGGER](http://pastebin.com/tcANMhen)。我在這裏間接使用「GROUP BY」。但它顯示相同的錯誤 – Imran

0

如果數據確實是相同的,你可以簡單地使用"min()"沒有GROUP BY /不同

UPDATE 
    product_stock AS S 
LEFT JOIN 
    product_purchase_item AS I 
ON 
    S.product_id=I.product_id AND S.product_size=I.product_size 
LEFT JOIN 
    product_purchases AS P 
ON 
    I.product_purchase_item_id=P.product_purchase_item_id 
SET 
    -- CHANGE HERE ===============================> 
    S.product_size_quantity=S.product_size_quantity+MIN(I.quantity) 
WHERE 
    S.product_id=? 
AND 
    S.product_size=? 
+0

同樣的問題。我不明白,爲什麼你使用MIN()?.可能是在SET之前發現的問題。因爲在這裏它已經獲得重複價值。 – Imran