为每个用户选择两个表的SUM

时间:2012-07-26 00:02:17

标签: mysql math join sum

我有一个带有users表,credit_purchase表和credit_spend表的应用程序。我试图获得用户目前拥有的信用额度。

信用表如下:

credit_purchase

+----+---------+-------+---------------------+
| id | user_id | coins | timestamp           |
+----+---------+-------+---------------------+

credit_spend

+----+---------+-------+---------------------+
| id | user_id | coins | timestamp           |
+----+---------+-------+---------------------+

我要做的是为每个用户选择SUM(credit_purchase.coins) - SUM(credit_spend.coins)。现在我有这样的事情:

SELECT users.*, COALESCE(SUM(credit_purchase.coins) - SUM(credit_spend.coins), 0) 
FROM users 
LEFT JOIN credit_purchase ON users.id = credit_purchase.user_id 
LEFT JOIN credit_spend ON users.id = credit_spend.user_id 
GROUP BY users.id

但是,结果不是正确的数字。这似乎是正确地对购买进行调整,但是将SUM与花费乘以购买数量。

我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT  users.*, 
        COALESCE(SUM(credit_purchase.coins) - SUM(credit_spend.coins), 0) 
FROM    users 
            LEFT JOIN credit_purchase
                    ON users.id = credit_purchase.user_id 
            LEFT JOIN credit_spend 
                    ON users.id = credit_spend.user_id 
GROUP BY users.id