MySQL 中 delete where in 語句的子查詢限制
- 場景一
delete from table1 where id = (select max(id) from table1 ); [Err] 1093 - You can’t specify target table 'table1 ’ for update in FROM clause
描述: 如果子查詢的 from 子句和更新、刪除物件使用同一張表,會出現上述錯誤。 解決方法: 通過給 from 子句中的結果集起別名。
delete from table1 where id = (select n.max_id from (select max(id) as max_id from table1 ) as n);
上述情況對於 in 子句也適用,in後面的子查詢不能帶where條件,帶where條件的必須使用別名
delete from table1 where id in (select id from table1 where id > 30); [Err] 1093 - You can’t specify target table 'table1 ’ for update in FROM clause
解決方法同上:
delete from table1 where id in (select n.id from (select id from table1 where id > 30) as n);
- 場景二
delete from table1 m where m.id = 1; [Err] 1064 - You have an error in your SQL syntax;
描述: delete from table 這樣的句子中 table 不能使用別名。 解決方法:去掉別名:
delete from table1 where id = 1;