2011-11-21 88 views
1

我一直在試圖將一個複雜的SELECT查詢轉換爲UPDATE查詢,但我不斷收到1064語法錯誤。將複雜的mysql SELECT轉換爲UPDATE

查詢的目標是更新滿足特定條件的某些行,但是連接和GROUP BY和HAVING語句使得我現在使用的查詢無法實現這一點。我知道這不是正確的方法,但我無法發現解決方案應該是什麼。如果有人能告訴我一個解決方案的方向,我會很棒!

我的查詢(該值是不正確的,但給一些更多的上下文):

UPDATE products p 
JOIN products_to_specifications pts ON pts.products_id = p.products_id 
JOIN products_specifications ps ON ps.specifications_id = pts.specifications_id 
SET p.products_image = 'file_name.jpg' 
WHERE ps.specifications_name IN ('color') 
AND pts.content IN ('black') 
AND p.products_manufacturer = 'BMW' 
AND p.products_name = 'M5' 
GROUP BY p.products_id 
HAVING COUNT(DISTINCT ps.specifications_name) = 1 AND COUNT(DISTINCT pts.content) = 1 

我的表結構:

表產品: products_id,products_image等(基本信息相同的每個產品)

表products_specifications: specifications_id,specifications_name

表products_to_specifications: products_id,specifications_id,內容

我認爲正確的解決方案,我將不得不使用子查詢,但我不知道如何構建查詢

回答

0

的MySQL不支持GROUP BY在UPDATE語句中。您可以通過將複雜查詢作爲派生表進行輕鬆更新,如下所示。

UPDATE products p, (SELECT p.products_id FROM products p 
JOIN products_to_specifications pts ON pts.products_id = p.products_id 
JOIN products_specifications ps ON ps.specifications_id = pts.specifications_id 
WHERE ps.specifications_name IN ('color') 
AND pts.content IN ('black') 
AND p.products_manufacturer = 'BMW' 
AND p.products_name = 'M5' 
GROUP BY p.products_id 
HAVING COUNT(DISTINCT ps.specifications_name) = 1 AND COUNT(DISTINCT pts.content) = 1) AS t 
SET p.products_image = 'file_name.jpg' WHERE p.products_id=t.products_id 

希望這可以幫助你。

+0

即使我看不到整個代碼......我認爲有一個錯字!你需要更換p。與t。在整個SELECT中(否則你無法通過t.products_id在最後的WHERE中訪問它) –