我有两个表,一个是帐户,另一个是account_trans,帐户表有关于个人帐户的记录,而在account_trans表中,所有交易都是根据帐户ID插入的。
帐户表有这些,
account_id, account_holder_name, .....
和 account_trans 表格包含以下字段,
trans_id, account_id, debit_amount, credit_amount ....
现在我想在单页显示所有帐户,同时我想显示每个帐户的余额(credit-debit=total-balance
)。我想使用单个mysql查询。
输出应该是这样的
Account Holder Name | Account Balance (Credit Amount - Debit Amount = Balance Amount)
Account Holder Name2 | Account Balance2 (Credit Amount2 - Debit Amount2 = Balance Amount2)
对此有任何建议......
答案 0 :(得分:0)
有很多方法可以做到这一点。其中之一如下。
我假设一个account_id在account_trans
表中有很多借方和贷方。
试试这个 -
SELECT accounts.account_holder_name
(acc.credit - acc.debit) AS balance
FROM accounts,
(SELECT account_id
SUM(IFNULL(debit_amount, 0)) debit,
SUM(IFNULL(credit_amount, 0)) credit
FROM account_trans
GROUP BY account_id) acc
WHERE accounts.account_id = acc.account_id