How to add a value to the current in each row of a mysql table?

Asked

Viewed 759 times

2

I have the following table in a mysql database:

Exemplo da tabela

I would like a command to run in phpmyadmin, which sums the current value of the rating_sum column with 5, and rating_count with 1, thus leaving:

inserir a descrição da imagem aqui

I want to add these values (5 , 1) to all rows of the table, without any restriction. I tried some things I found here in the OS, but they were examples to display the total value of a certain column, and it’s not what I need.

How could I?

  • SELECT *, ( rating_sum + 5 ), ( rating_count + 1 ) FROM TABELA

  • @Marceloboni hello, the command you passed, only creates two new columns with the added values, but does not change the values already present in the table, I tried to adapt to UPDATE DATABASE.TABLE SET `, ( rating_sum + 5 ), ( rating_count + 1 ); but gives a syntax error.

  • A ta, I get it, UPDATE BANCO.TABELA SET rating_sum = ( rating_sum + 5 ), rating_count = ( rating_count + 1 );

  • @Marceloboni thank you very much, it worked exactly as you would like, can add as reply to mark as resolved please?

1 answer

2


When you want to do a sum update (among other operations) of a column in all rows of a table, just reference the column itself in the update without defining a where (this will cause all rows in the table to be updated). In each row will be used the value already filled in the fields.

In your case, something like that:

UPDATE BANCO.TABELA SET rating_sum = ( rating_sum + 5 ), rating_count = ( rating_count + 1 );

  • thank you very much for the explanation, exactly what you needed

  • 1

    I hesitated to put as an answer because of the two: this type of operation has always been kind of automatic for me, I find it difficult to put in words, according to which probably should already have something on the network, anyway I created the answer as wiki, so anyone who wants to update the answer, adding more information, or correcting what I "tried to explain", I will be grateful =)

Browser other questions tagged

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