0
Good afternoon! I have an SQL query, which searches and sums up the amount of credits a given user has:
SELECT *, SUM(quantidade) as total_creditos FROM creditos INNER JOIN usuarios ON creditos.id_usuario = usuarios.id WHERE creditos.id_usuario = '$id_usuario'`
In the credit table, I have the following structure:
A user can have multiple Inserts in the table, with X credits.
The question is: can I make a query and decrease (delete) a Y value of a user’s total SUM of credits?
Thanks in advance!
What is the condition of the value to be replaced? A certain credit id, user...?
– Gustavo Jantsch
User ID. It is at the end of the query. It would be the consumption of a given item... any value, but would have to change in the table!
– Guilherme Lirio
One way you can replace it is not to include it in SUM(), that is, filter this value in the query by adding this condition in WHERE along with the user ID that is already there, or using the IF function inside the SUM to replace it with zero. Another possibility is to subtract this value with a SUM(quantity) - (SELECT...) subquery. What was not clear to me is the criterion that identifies the "given item" so that a solution can be created with it.
– Gustavo Jantsch
So Gustavo, in my case, the user will enjoy his available credit (determined by himself the amount). But as @Emerson Ferreira Bezerra explained to me, the bank was unviable from my way of thinking. I ended up doing as he suggested: create the debit field and do the calculation to know the current amount of user credits:
SELECT *, (SUM(credito) - SUM(debito)) as total_creditos FROM creditos INNER JOIN usuarios ON creditos.id_usuario = usuarios.id WHERE creditos.id_usuario = '$id_usuario'
– Guilherme Lirio