MySQL 中 delete 語句的子查詢限制
阿新 • • 發佈:2019-01-31
場景一
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;