eNe*_*tcH 1 php mysql transactions codeigniter activerecord-calculations
我正在尝试为 Web 应用程序实现钱包。我现在提出的数据库设计是一个钱包交易表,如下所示:
wallet_tr_id | user_id | amount | tr_type (debit/credit) | datetime | tr_id
Run Code Online (Sandbox Code Playgroud)
应用程序中的用户可以通过现金或钱包信用进行交易。还有另一个 transactions表保存所有交易信息,通过钱包信用支付/赚取的信息使用外键输入到上表中tr_id。
现在显示用户他/她当前钱包余额的最佳方式是什么?
我应该sum total of credits - sum total of debits为该用户计算,还是应该current_balance在其他表中为用户维护?
PS:最终不会有任何用户的大量交易。
无需存储余额。就按照你说的计算一下:
select sum(case when tr_type = 'credit' then amount else -amount end) as balance
from transactions
where user_id = 12345;
Run Code Online (Sandbox Code Playgroud)