How to update the database with SELECT Sum

2

I need to do update of a table by adding two values (money + deposited), thus getting 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 above value in the table and I can not get it like this:

UPDATE usuarios SET total=(Select SUM(dinheiro)+(depositado) total from usuarios WHERE id=1)
    
asked by anonymous 27.07.2018 / 16:56

1 answer

3

So?

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

Understand the columns as variables. You do not have to do anything crazy to get your values. Just get the variable that in that row will have the value of the column, nothing more of this. Do not try to use things without knowing. It's not simple. What this is doing is to take the value of two columns, adding up, and setting up another column. That simple. in this case it will be done only on the user that has id equal to 1. If taking this where will be done on all users, each user will have his own sum isolated from the others. If you know programming imperatively in programming language it's like a for . When you enter where it's like you have if inside that for . If the database was properly modeled it will be very fast because it has optimization. If you can not model and have lots of data, it will be tragic.

The first select does not make the slightest sense, it works by coincidence.

It will be more tragic to work well and find 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.

In addition to knowing and understanding and communicating your problem is something that comes even before programming.

    
27.07.2018 / 17:16