考慮到開發人員有時候不小心誤更新資料,要求線上庫的 MySQL 例項都設定 sql_safe_updates=1 來避免沒有索引的 update、delete。
結果有一天開發發現下面的一個SQL 沒法正確執行:
update t1 set col2=1 where key1 in (select col2 from t2 where key2='ABcD');
錯誤如下:
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column
也就是說沒法對沒有走到索引的where條件進行更新。搜尋了下發現,的確不行。及時 key1 和key2 分別是 t1、t2 的索引[我換成主鍵都不行] 。說明是不支援子查詢的update。
google 了一下發現人家也問過這個問題。。
最後解決方法:
1)修改 session 級別的引數: set sql_safe_updates=0; 執行 update 操作。退出終端。
2)程式處理:先 select col2 from t2 where key2='ABcD' 獲取資料,然後迴圈處理結果,並用 update t1 set col2=1 where key1=? 來批量更新過。建議還是用程式處理,臨時修改變數不是長久之計。