關於mysql 5.7版本「報[Err] 1093 - You can't specify target table 'XXX' for update in FROM clause」錯誤的bug

不一樣於oracle和sqlserver,mysql並不支持在更新某個表的數據時又查詢了它,而查詢的數據又作了更新的條件,所以咱們須要使用以下的語句繞過:html

UPDATE teaching_department SET code_year = 2017, notice_code = (SELECT a.code + 1 FROM (SELECT MAX(notice_code) code FROM teaching_department WHERE department_id = 6284 and code_year = 2017) a) WHERE id = 106;

本地測試是經過的,可是在上到測試環境的時候,發現仍是會報以下錯誤:mysql

[SQL] UPDATE teaching_department SET code_year = 2017, notice_code = (SELECT a.code + 1 FROM (SELECT MAX(notice_code) code FROM teaching_department WHERE department_id = 6284 and code_year = 2017) a) WHERE id = 106;
[Err] 1093 - You can't specify target table 'teaching_department' for update in FROM clause

對比版本發現,本地是5.6.25,測試環境是5.7.10,版本高的反而不支持了。只能改用另外一種方式實現:sql

UPDATE teaching_department, (SELECT MAX(notice_code) code FROM teaching_department WHERE department_id = 6284 AND code_year = 2017) AS t SET code_year = 2017, notice_code = t.code + 1 WHERE id = 7

這種寫法在各版本都是支持的。語法見UPDATE Syntaxoracle

 

後來發現,這是mysql 5.7.6版本出現的一個bug,而且在5.7.11版本中修復了。參考sqlserver

相關文章
相關標籤/搜索