There is a request:

INSERT INTO `DonateCoins` (`player`, `donateCoins`) VALUES ('test', '20202') 

How to make, that at performance of the given request, if such player present in the table, then to its quantity of coins 20202 is added?

In the table itself there is a player - test and donateCoins - 0

  • one
    google: // unique key insert update mysql, and get used to show create table %tableName% result show create table %tableName% when you ask sql-related questions, and specify the exact name of the database in the tag. is it mssql, sql, firebird, postgres? - strangeqargo
  • Thank you for correcting the message. - MrTrojan

1 answer 1

You can do the following: we index the player column with a unique index

 ALTER TABLE DonateCoins ADD UNIQUE KEY player (player); 

This will not allow duplicate records to be inserted into the DonateCoins table. We insert new data with an INSERT request with ON DUPLICATE KEY UPDATE , in which we write the logic for updating the field when an insert record is detected with an already existing player.

 INSERT INTO DonateCoins (`player`, `donateCoins`) VALUES ('test', '20202') ON DUPLICATE KEY UPDATE donateCoins = donateCoins + VALUES(donateCoins); 

As a result, if the entry already exists, donateCoins will increase by 20202 (the column type must be numeric, not text).

  • Thanks, I'll try now. UPD: works, everything. - MrTrojan