How to update the database with SELECT Sum

Asked

Viewed 354 times

2

I need to do the update of a table summing two values (money + deposited), thus obtaining the total. This total I already have using the code

Select SUM(dinheiro)+(depositado) total from usuarios WHERE id=1

But I wanted to put the value up on the table and I didn’t get it so:

UPDATE usuarios SET total=(Select SUM(dinheiro)+(depositado) total from usuarios WHERE id=1)

1 answer

3


Thus?

UPDATE usuarios SET total = dinheiro + depositado WHERE id = 1

I put in the Github for future reference.

Understand the columns as variables. You don’t have to do anything crazy to get your values. Just take the variable that in that row will have the column value, nothing else. Don’t try to use things without knowing. Go to simple. What this is doing is taking the value of two columns, adding them up, and storing them in another column. Simple as that. in this case will be done only on the user who has the id equal to 1. If you take this where will be done on all users, each user will have their own sum isolated from the others. If you know programming imperatively in programming language is like a for. When does the where it’s like I have a if within that for. If the database has been modeled properly it will be very fast because it has optimization. If you do not know how to model and have a lot of data it will be tragic.

The first select doesn’t make any sense, it works by coincidence.

Fiat 147 todo detonado andando pelas ruas

It will be more tragic to function well and think that this is how it is done. The ideal is to learn the concepts before doing anything. Contrary to what is preached around programming is not easy.

Besides knowing and understanding and communicating your problem is something that comes up before programming.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.