假设tb_a 表 有两个字段 id,amount
id | amount(金额) |
1 | 12.00 |
2 | 23.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不会出现此问题。我暂时未测试过)
参考资料: