MySQL中 You can't specify target table for update in FROM clause 问题的解决办法

假设tb_a 表 有两个字段 id,amount 

idamount(金额)
112.00
223.45

我们要把id为2的金额全部 减去然后 给id为1的人

update tb_a set  amount = amount +(select amount from tb_a where id=2) where id =1;

然后会报错:You can't specify target table for update in FROM clause

经过测试发现:在 update或者delate时会发生这个问题。

MySQL中You can't specify target table for update in FROM clause错误的意思是说,不能先select出同一表中的某些值,再update这个表(在同一语句中)

原因分析:

MySQL 修改或者删除数据时候不能以当前表作为 from 条件。

解决版本,把作为调节的查询结果再包一层作为临时表即可,把上面脚本修改如下:

update tb_a set  amount = amount +(select temp.amount from (select amount from tb_a where id=2) temp ) where id =1;

也就是说将select出的结果再通过中间表select一遍,这样就规避了错误。

(资料中说:注意,这个问题只出现于mysql,mssql和Oracle不会出现此问题。我暂时未测试过)

 

参考资料:

https://www.cnblogs.com/jeffen/p/7016547.html

https://blog.csdn.net/jsloveyou/article/details/79024600

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值