MYSQL:如何从三个表中返回查询计算结果?

时间:2014-08-16 08:10:09

标签: mysql

我有三张桌子:

Table1: Salary
Fields: ID,Account_Num,Amount

Table2: Other_Income
Fields: ID,Account_Num,Amount

Table3: Expenses
Fields: ID,Account_Num,Amount

从上表中,如何编写返回结果的查询,列出这些表中的所有帐户,并显示这些表中每个帐户的余额。

结果应显示Account_num,Salary,Other_Income,Expenses, balancebalance=Salary.amount+Other_Income.amount-expenses.amount

这三个表可能包含一些不同的帐号。

我一直在考虑这么久,尝试过联盟和加入,但仍然无法做到。

有人出示/指导我?

3 个答案:

答案 0 :(得分:0)

我对以下查询运气不错。基本上,我将Salary,Other_Income和Expenses表中的所有事务组合成一个名为combined的临时表,然后使用group by来汇总所有事务!

select Account_Num, sum(Amount)
from (
  select Account_Num, Amount from Salary union
  select Account_Num, Amount from Other_Income union
  select Account_Num, -Amount from Expenses
) as Combined
group by Account_Num;

答案 1 :(得分:0)

以下查询可能会有所帮助,前提是每个帐户都有相应的工资。

select  Account_Num,(total-d.Amount) as final_amount ( select Account_Num, ifnull(a.Amount,0)+ifnull(b.Amount,0) as total from Salary a
   left join Other_Income b on a.Account_Num=b.Account_Num ) c
   join Expenses d on c.Account_Num=d.Account_Num 

答案 2 :(得分:0)

    SELECT Sal.`Account_Num`, sal.`Amount` AS Salary, ot_in.`Amount` AS ExtraIncome , exp.`Amount` AS expenses, (sal.`Amount`+ot_in.`Amount`-exp.`Amount`) As Balance FROM Salary AS Sal INNER JOIN Other_income AS ot_in ON Sal.`Account_Num` = ot_in.`Acount_num` INNER JOIN Expenses AS exp ON Sal.`Account_Num` = ex.`Account_Num`   

这里加入三个表,条件是你从这三个中获得公共账号并从每个中提取相应的金额,用给定的公式计算剩余余额从收入中扣除费用。我跳这将有所帮助。