背景
在测试环境进行需要清理无效数据,在 delete 的时候,发现按照 select 的语法使用子查询无法删除数据。
错误语句
delete from goods_show where id in (select goods_show.id as id from goods_show left join goods on goods_show.goods_id = goods.id where goods.id is null);
报错:
You can't specify target table 'goods_show' for update in FROM clause
问题 :
如果子查询的 from 子句和更新、删除对象使用同一张表,会出现上述错误。
解决
方案一: 加别名
给子查询的结果做别名,使得子查询与from对象不是同一个表。
参考SQL
delete from goods_show where id in (select id from (select goods_show.id as id from goods_show left join goods on goods_show.goods_id = goods.id where goods.id is null) as A);
方案二: 语法修改
使用语法:
delete a from a,(select id from XXXX where XXX) b where a.id = b.id
来修改SQL语句。
参考:
delete goods_show from goods_show,(select goods_show.id as id from goods_show left join goods on goods_show.goods_id = goods.id where goods.id is null) B where goods_show.goods_id = B.id;
在测试环境中删除无效数据时,如果在DELETE语句中使用子查询,且子查询的FROM子句与被删除的表相同,会出现错误。文章提供了两种解决方案:一是给子查询结果添加别名,二是使用特定的DELETE语法结构,避免直接引用目标表。这两种方法都可以成功执行删除操作。
1439

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



