mysql> select * from t;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
+----+
10 rows in set (0.00 sec)
mysql> delete from t where id in (select id from t where id < 5);
ERROR 1093 (HY000): You can't specify target table 't' for update in FROM clause
mysql>
这样删除将报错,更改SQL语句为
mysql> delete from t where id in (select * from (select id from t where id < 5) tmp);
Query OK, 4 rows affected (0.00 sec)
以这样的形式即可删除。
再优化之,改为表连接模式:
mysql> delete t from t join (select id from t where id < 5) tmp on t.id=tmp.id;
Query OK, 4 rows affected (0.01 sec)
转自 [url]http://hcymysql.blog.51cto.com/5223301/895517[/url]
本文介绍了一种在MySQL中批量删除特定记录的有效方法。通过对比不同的SQL语句,展示了如何避免因目标表出现在FROM子句中而导致的错误,并给出了使用子查询和表连接两种优化方案。
516

被折叠的 条评论
为什么被折叠?



