2012-05-31 62 views
-3

我有两个表,一个是帐户,另一个是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

谷歌加入 – Shiven

回答

0

有很多方法可以做到这一点。其中之一如下。 我假设一个account_id在account_trans表中有很多借方和贷方。

试试这个 - 你post.Look内心之前

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