数据
需求
- 将充值类型为2的记录的充值金额改为相同批次id充值类型为1的充值金额的5%
- 上表中数据是处理之后的效果
操作
-
错误操作:
-- 将充值类型为1的 充值金额*5% 设置为充值类型为2且相同batch_id相同的记录的充值金额 update recharge_record a set a.recharge_amount = (SELECT b.recharge_amount from recharge_record b WHERE b.recharge_type = 1 AND a.batch_id = b.batch_id )/20 WHERE a.recharge_type = 2
注意:
- 报错内容:You can’t specify target table ‘a’ for update in FROM clause(不能在select中指定要更新的表a)
-
正确操作:
-- 先多表进行关联,这里使用的是同一个表,指定关联条件。 -- where条件需要放到set语句之后 update recharge_record a JOIN recharge_record b on a.batch_id = b.batch_id set a.recharge_amount = b.recharge_amount/20 where a.recharge_type = 2 and b.recharge_type = 1