ERROR 1093 (HY000): You can't specify target table 'b' for update in FROM clause

今天开发大神说有一个update的普通sql执行有问题,抱怨mysql太烂,后来看了sql后发现原来是update 更新使用where条件使用了本身表的子查询的问题,不得不说mysql有这方面的限制不过绕一绕也是可以的,当然最后还是让开发心满意足的离开了。

这个限制其实早就存在,包括mysql及其mariadb (甚至是10.0.6)只不过我忘了告诉开发的大神们,这次记录一下,也许其他不知道写法的大神百度能度到这篇文章,好了废话少说!

测试过程如下:

create table up(id int ,name varchar(20));

 insert into up values(1,'1'),(2,'2'),(1,'3');

执行update 如下:


MariaDB [test]> update up b set id=0 where id=(select distinct(id) from up a where a.id=b.id);

ERROR 1093 (HY000): You can't specify target table 'b' for update in FROM clause

改写(1)- join:

MariaDB [test]> update up as b,(select distinct(id) from up a ) as c  set b.id=0 where c.id=b.id ;
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0

改写(2)- 子查询之子查询:

MariaDB [test]> update up b set id=0 where id=(select id from (select distinct(id) from up k) a where a.id=b.id); 
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0

说白了,就是原始表不能出现在where 后面第一层的子查询当中,至于两种改写的性能的看具体业务和数据量的大小。

就简单记录到此,希望对你有用。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值