2014-10-04 44 views
3

我想寫這樣的查詢,我得到一個錯誤。這是我第一次使用案例,所以這就是我認爲問題所在的地方。查詢使用CASE當

UPDATE my_table 
     CASE 
       WHEN downloads IS NULL THEN 
       SET downloads = 1 
       ELSE 
       SET downloads + 1 
     END 
WHERE attachment_id = 8990 
AND parent_post_id = 9221 
OR  attachment_id = 9211 
AND parent_post_id = 383 
+0

備份一下。 CASE表達式返回一個值。您可以在語句中使用CASE表達式,例如列名的位置。你可以沿着這條線進行一些操作** UPDATE t SET t.col = CASE WHEN t.col IS NULL THEN 1 ELSE t.col + 1 END WHERE ... ** – spencer7593 2014-10-04 18:35:42

回答

5

你可以把它改寫如下

UPDATE my_table 
SET downloads = CASE WHEN downloads IS NULL THEN 1 
       ELSE downloads + 1 END 
WHERE attachment_id = 8990 
AND (parent_post_id = 9221 
OR attachment_id = 9211) 
AND parent_post_id = 383 

你也爲了配合9211parent_post_idattachment_id使用或操作時需要組()or條件,也有你有混亂情況在您的查詢如何parent_post_idattachment_id可以等於2個值同時可能你正在尋找

WHERE (attachment_id = 8990 AND parent_post_id = 9221) 
OR (attachment_id = 9211 AND parent_post_id = 383) 
1

update s語法是​​。使用case不會改變這一點。 case只能用於返回表達式,所以:

UPDATE my_table 
SET downloads = CASE WHEN downloads IS NULL THEN 1 ELSE downloads + 1 END 
WHERE attachment_id = 8990 AND 
     parent_post_id = 9221 OR 
     attachment_id = 9211 AND 
     parent_post_id = 383