start transaction 1.SELECT balance FROM user where user_id = #{userId} for update; 2. int affectRows = update user set balance=balance-100 where user_id = #{userId} and balance>=100; 3. if(affectRows > 0){ commit; }else{ rollback; }
stonewu
2022-04-03 21:21:02 +08:00
update user set balance = balance - 你要扣除的金额 where balance - 你要扣除的金额 >= 0 and id=用户 ID;
jasonkayzk
2022-04-03 21:25:43 +08:00
这么经典的问题,用乐观锁不就解决了:
update user set balance=balance-? where id=? and balance>=?;