-3

我有两张表,一张是accounts,一张是account_trans,accounts 表有关于个人账户的记录,account_trans 表中所有的交易都是根据account 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)

对此有任何建议...

4

1 回答 1

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
于 2012-05-31T11:29:24.753 回答