mysql update使用子查询

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/p_3er/article/details/51083743

今天我像以前操作Oracle写了一个update sql:

update device_user a set a.scene_id=null 
where a.id not in(select min(t.id) from device_user t group by t.device_id);

根据子查询的结果,更新表中的一个字段。

在mysql数据库中执行后报错:

Error Code: 1093. You can't specify target table 'a' for update in FROM clause

一直没弄明白这个错误,然后经过多次度娘后,发现mysql update时,更新的表不能在set和where中用于子查询。

修改上面的sql为mysql数据库支持的方式:

update device_user du, 
(select id from device_user where id not in(select min(t.id) from device_user t group by t.device_id)) b 
set du.scene_id=null 
where du.id=b.id;

猜你喜欢

转载自blog.csdn.net/p_3er/article/details/51083743