MYSQL 1093 - You can't specify target table '' for update in FROM clause

在尝试删除重复数据时遇到MySQL错误1093,该错误因在同一子查询中更新目标表而发生。文章介绍了问题原因,并提供了解决方案,包括使用中间结果集和JOIN操作来规避此限制,提高SQL执行效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有一次由于不太熟悉业务,忘了加唯一索引,导致数据库里不少重复数据。为了删除重复数据,编写下面的SQL语句,但是执行完后却报了如标题的错误。原因是:MySQL不允许在进行子查询的同时删除原表数据

 

[sql]   view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. DELETE FROM table1  
  2.     where order_id in  
  3.         (select order_id from table1 group by order_id having count(order_id) > 1)  
  4.     and id not in  
  5.         (select min(id) from table1 group by order_id having count(order_id)>1);  


        其中的一个解决办法如下,就是在将查询结果作为一个结果集,再从这个结果集中取数据,然后保留最小id的数据。SQL如下(第2,3,4,9,10为新添加的)。

[sql]   view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. delete from table1  
  2.   where id in (  
  3.         select id from (  
  4.             select id from table1  
  5.                 where order_id in  
  6.                 (select order_id from table1 group by order_id having count(*) > 1)  
  7.                 and id not in  
  8.                 (select min(id) from table1 group by order_id having count(*)>1)  
  9.         ) as t  
  10.     );  

 

       上面的sql给DBA看到后,立马就给喷了,说这样执行太低,于是修改成下面这样:

 

[sql]   view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. delete a from table1 a ,  
  2.     (select min(id) as ms ,order_id from table1 group by order_id having count(*)>1) b  
  3.         where a.order_id=b.order_id and a.id>b.ms  

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值