Best way to prevent a value from going negative in mysql

前端 未结 3 1334
鱼传尺愫
鱼传尺愫 2021-01-28 19:46

We have a table that maintains account balances by recording transactions in that table. i.e. the most recent row is the account balance.

When recording a withdrawal, we

3条回答
  •  [愿得一人]
    2021-01-28 19:55

    Why don't you just do:

    INSERT INTO `txns`
      (`account_id`, `prev_balance`, `txn_type`, `new_balance`,  `amount`, `description`)
    SELECT *
    FROM (
     SELECT
      t.account_id, t.new_balance, $txn_type, t.new_balance - $amount, $amount, $description
     FROM `txns` t
     WHERE t.account_id = '$account'
     ORDER BY txn_id desc
     LIMIT 1
    )
    WHERE new_balance - $amount > 0
    

提交回复
热议问题