小编典典

用于查询帐户余额的SQL查询

sql

我想使用原始sql来计算帐户余额,而无需额外的应用程序逻辑。交易模式包括金额,from_account_id和to_account_id

我的查询是

SELECT SUM(tdebit.amount) - SUM(tcredit.amount) as balance
FROM accounts as a
INNER JOIN transactions as tdebit ON a.id = tdebit.to_account_id
INNER JOIN transactions as tcredit ON a.id = tcredit.from_account_id
WHERE a.id = $1 AND tdebit.succeed = true AND tcredit.succeed = true

而且它没有按我预期的那样工作-结果是错误的,但是如果我仅在事务正常运行后才加入交易,例如只需借记金额就可以

SELECT SUM(tdebit.amount) as debit
FROM accounts as a
INNER JOIN transactions as tdebit ON a.id = tdebit.to_account_id
WHERE a.id = $1 AND tdebit.succeed = true

我在余额查询中错过了什么?

http://sqlfiddle.com/#!15/b5565/1


阅读 208

收藏
2021-04-07

共1个答案

小编典典

基本上,您正在计算atdebits和之间的叉积tcredits,即,对于tdebits您中的每一行,都要对中的所有行进行迭代tcredits。也没有理由加入accounts(除非to_account_id并且from_account_id不是外键)。

您只需要进行一次转账交易,您只需要知道金额是贷方还是借方。

SELECT SUM(CASE WHEN t.to_account_id = $1 THEN t.amount ELSE -t.amount END) AS amount
FROM transactions AS t
WHERE (t.to_account_id = $1 OR t.from_account_id = $1)
  AND t.succeed = true

如果帐户可以转账至自己,请添加一个t.to_account_id <> t.from_account_id

2021-04-07