今天在尝试用子查询来关联更新一个表的收到如下报错:
ERROR 1093 (HY000): You can't specify target table 'v_member_info' for update in FROM clause
具体执行的sql如下:
MySQL [meminfo]> update v_member_info set cust_right_group=0 where id in (select id from v_member_info where pay_end_date<'2018-01-29' and cust_right_group>0);
ERROR 1093 (HY000): You can't specify target table 'v_member_info' for update in FROM clause
原来是mysql在update的时候, 原始表不能出现在where 后面第一层的子查询中;
解决办法:两种改写方法
1)改写成join方式更新
MySQL [meminfo]> update v_member_info as a ,(select id,cust_right_group from v_member_info where pay_end_date<'2018-01-29' and cust_right_group>0) as b set a.cust_right_group=0 where a.id=b.id;
Query OK, 288 rows affected (2.35 sec)
Rows matched: 288 Changed: 288 Warnings: 0
2)或者改成子查询之子查询
MySQL [meminfo]> update v_member_info set cust_right_group=0 where id in(select id from (select id from v_member_info where pay_end_date<'2018-01-29' and cust_right_group>0)a);
小结:Oracle和MySQL还是有区别的,MySQL在update的时候,原始表不能出现在where 后面第一层的子查询当中,至于两种改写的性能的看具体业务和数据量的大小。