I have an application with a users table, credit_purchase table, and credit_spend table. I am trying to get the amount of credits the user currently has.
The credit tables are as follows:
credit_purchase
+----+---------+-------+---------------------+
| id | user_id | coins | timestamp |
+----+---------+-------+---------------------+
credit_spend
+----+---------+-------+---------------------+
| id | user_id | coins | timestamp |
+----+---------+-------+---------------------+
What I’m trying to do is select the SUM(credit_purchase.coins) – SUM(credit_spend.coins) for each user. Right now I have something like this:
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
but, it the result is not the correct number. It seems to be SUMing the purchases properly, but multiplying the SUM from the spend by the number of purchases.
What am I doing wrong?
Thanks!
try this: