您的位置:首页 > 其它

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

2014-01-02 14:44 387 查看
今天开发大神说有一个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 后面第一层的子查询当中,至于两种改写的性能的看具体业务和数据量的大小。

就简单记录到此,希望对你有用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐