我有一个如下表:
transaction_id
user_id
other_user_id
trans_type
amount
此表用于维护财务类型应用的帐户交易.
它的双重记录会计,因此从用户A到B的转移会在表格中插入两行,如图所示.
1, A, B, Sent, -100
1, B, A, Received, 100
任何帐户的余额都是通过汇总该帐户的交易来计算的.
例如:
select sum(amount) from transactions where user_id=A
锁定资金转移的最佳方法是什么?我目前的代码如下:
Start Transaction
Debit the sender's account
check the balance of the sender's account
if new balance is negative then the sender didn't have enough money and rollback
if the balance is positive then credit the receiver and commit
这似乎与预期完全不同.我在网上看到很多关于基本上说的交易的例子:开始,借记发送者,信用接收者,提交.但检查发件人之间的平衡的最佳方法是什么?
我有交易通过,不应该.假设一个用户有3K的余额,并且两个交易在3K完全同时进入,当这两个交易只有一个时,它们都会通过.
谢谢
解决方法:
您使用的是InnoDB表还是MyISAM表? MySQL不支持MyISAM表上的事务(但如果你尝试使用它们,它不会给你一个错误).另外,请确保您的事务隔离级别设置正确,它应该是SERIALIZABLE,这不是MySQL的默认值.
这个article有一个很好的例子,它使用一个非常类似于你的例子来解释不同隔离级别的影响.
标签:mysql,transactions
来源: https://codeday.me/bug/20190527/1161147.html