0

我有一个带有 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 乘以购买次数。

我究竟做错了什么?

谢谢!

4

1 回答 1

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
于 2012-07-26T00:08:17.977 回答