MySQL 中 delete 語句的子查詢限制


場景一


delete from student where id = (select max(id) from student);

[Err] 1093 - You can't specify target table 'student' for update in FROM clause

描述: 如果子查詢的 from 子句和更新、刪除對象使用同一張表,會出現上述錯誤。

解決方法: 通過給 from 子句中的結果集起別名。


delete from student where id = (select n.max_id from (select max(id) as max_id from student) as n);

上述情況對於 in 子句也適用


delete from student where id in (select id from student where id > 30);

[Err] 1093 - You can't specify target table 'student' for update in FROM clause

解決方法同上:


delete from student where id in (select n.id from (select id from student where id > 30) as n);

場景二


delete from student m where m.id = 1;

[Err] 1064 - You have an error in your SQL syntax;

描述: delete from table 這樣的句子中 table 不能使用別名。

解決方法:去掉別名:


delete from student where id = 1;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM