基本上,您正在计算a
tdebits和之间的叉积
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 amountFROM transactions AS tWHERe (t.to_account_id = $1 OR t.from_account_id = $1) AND t.succeed = true
如果帐户可以转账至自己,请添加一个
t.to_account_id <> t.from_account_id。



