Sum in sql update

2

I'm running the following sql in my mysql:

UPDATE 'cadastro' SET 'pontos'= 'pontos + 1' WHERE id = 102;

I need to update the column table every time the column table is made that is of type int(11)

When I run this sql it does not return an error, however, the pontos field always continues with a value of 1.

    
asked by anonymous 27.06.2017 / 21:27

2 answers

6

You're trying to add a string, try the following:

UPDATE 'cadastro' SET 'pontos' = 'pontos' + 1 WHERE id = 102;

Remembering that to work the column points must be of a numeric type. Example: int , double , float , etc ...

    
27.06.2017 / 21:31
3

Solution to a non-competitive scenario :

UPDATE cadastro SET pontos = pontos + 1 WHERE id = 102;

A very important consideration when doing this type of update is the concurrence of write accesses in the cadastro table.

If two clients run UPDATE up simultaneously, the data contained in the pontos field runs the risk of not getting as expected.

The solution for a concurrent scenario would be this:

START TRANSACTION;

-- Recupera O valor para atualização
SELECT pontos FROM cadastro WHERE id = 102 FOR UPDATE;

-- Incrementa o contador
UPDATE cadastro SET pontos = pontos + 1 WHERE id = 102;

COMMIT;
    
27.06.2017 / 21:54