一種方法是使用反連接模式,例如
UPDATE player_items p
LEFT
JOIN (SELECT uid
FROM player_items
WHERE slot = 12
AND uid = 2
LIMIT 1
) q
ON q.uid = p.uid
SET p.slot = 20
WHERE p.id = 0
AND p.uid = 2
AND q.uid IS NULL
LEFT JOIN查找匹配的行,但如果找不到匹配的行,那麼MySQL將生成一個包含所有NULL值的行。我們可以使用q.uid IS NULL
謂詞過濾掉任何匹配的行,因此我們只會在沒有匹配的情況下獲取行。
mysql> UPDATE player_items p
-> LEFT
-> JOIN (SELECT uid
-> FROM player_items
-> WHERE slot = 12
-> AND uid = 2
-> LIMIT 1
-> ) q
-> ON q.uid = p.uid
-> SET p.slot = 20
-> WHERE p.id = 0
-> AND p.uid = 2
-> AND q.uid IS NULL
-> ;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
spencer7593這不是工作:(我在我的MySQL得到一個錯誤和SQL小提琴(架構創建失敗:您的SQL語法錯誤;檢查對應於您的MySQL服務器版本正確的語法手冊在'UPDATE player_items'附近使用 – user2573981
第二個選項不起作用:( – user2573981
我有SET子句位置錯誤,它屬於WHERE子句之前,我修改了查詢,它似乎對我有用。 – spencer7593