Hi all,
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 would like to ensure that the balance can never go negative. Our proposed solution is something like:
INSERT INTO `txns`
(`account_id`, `prev_balance`, `txn_type`, `new_balance`, `amount`, `description`)
SELECT
t.account_id, t.new_balance, $txn_type, t.new_balance - $amount, $amount, $description
FROM`txns` t
WHERE t.account_id = '$account'
AND (select new_balance
FROM txns
WHERE account_id = '$account'
ORDER BY txn_id desc limit 1) >= $amount
ORDER BY txn_id desc LIMIT 1;"
But we are a bit concerned about the performance if the ANDed subquery (we had subquery performance issues on a previous project). None of the developers here are sql specialists. Deposits do not have the additional clause.
This is all on MySQL 5.0