来自2个不同表的SUM 2字段

时间:2014-10-16 13:28:07

标签: mysql sql

我有一个像这样的mysql查询:

SELECT SUM(bills.Amount) AS AmountExpense, SUM(assets.Amount) as AmountIncome 
FROM bills, assets where bills.UserId = 11 and assets.UserId =11

样本账单表

id  payee  description  UserId          Amount 
1  john   advance          11           15.0         
2  dave   request          2            13.0 
3  er     request          11           12.0   

示例资产表

id  payee  description  UserId          Amount 
1  john   advance          11           40.2        
2  dave   request          2            13.0
3  ww     request          11           14.00

我有AmountExpense的问题,多次记录SUM记录。我在Amount Income方面取得了成功。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

在这些表中的一个或两个表上,每个用户最多可能有一行。执行聚合后,您需要加入它们。另外,请不要使用旧式非ANSI隐式连接:

SELECT AmountExpense, AmountIncome
FROM (  SELECT  UserId, 
                SUM(Amount) AS AmountExpense
        FROM bills
        GROUP BY UserId) AS b
LEFT JOIN ( SELECT  UserId,
                    SUM(Amount) AmountIncome
            FROM assets
            GROUP BY UserId) AS a
    ON b.UserId = a.UserId
WHERE b.UserId = 11

答案 1 :(得分:0)

如果您有可能用户可以在任何一个表中,而不能在另一个表中,那么您需要等同于full outer join。 MySQL不支持该语法,但它支持这一点:

select userid, sum(amountexpense) as amountexpense, sum(amountincome) as amountincome
from (select userid, amount as amountexpense, null as amountincome
      from bills
      union all
      select userid, null, amount as amountincome
      from assets
     ) ba
group by userid;