I have a MySQL-Database where I run certain Stored Procedures.
In one of them, I want to sum up the amount a certain user has to pay, the amount he already payed and return all the users, where the amount to be payed isn't equal the amount paid. I came up with the following (simplyfied) query:
SELECT userId, SUM(costs) as sum_costs,
(SELECT SUM(payed)
FROM payments p WHERE ta.userId=p.userId) as sum_payed
FROM ta
GROUP BY ta.userId
ORDER BY ta.userId;
This gives me the sum of the costs and the payment for each user. But I do not know, how I can select only the users, where costs and payment are not equal.
WHERE sum_costs != sum_payed
doesn't work, because mysql doesn't know the column 'sum_costs' in the WHERE-clause.
Any idea, how to get the selection to work?