The goal is this: if there is an entry with such an id , then we increment the value in the count column of this row, and if not, we create a new entry (the count column is set to DEFAULT 0 ). Database - MySQL.

Of course, you can do several checks and implement such logic through the conditions in the programming language itself, but is it possible to do all this with a single SQL query (so that it works quickly), or at least make it somehow more elegant?

1 answer 1

 INSERT INTO `table` (`id`) VALUES (123456) ON DUPLICATE KEY UPDATE `count`=`count`+1; 
  • UPDATE happen exactly to the record, which has id = 123456? - LNK
  • one
    UPDATE is performed if INSERT reveals a violation of the uniqueness of any unique index. In this case, it will be executed UPDATE of exactly the record, the presence of which caused a violation of uniqueness. If the inserted data violates the requirement of the uniqueness of several indexes, the restriction of the index that has the smallest identifier in the table structure will work. - Akina