There is a table. I need to insert a string into it if it does not exist, or to update it if the entry already exists.

So far I’m doing this: I’m trying to get the data I need in one of the fields, then I check if I’ve returned something, if yes, I’m updating it, if not, I’m creating a new record.

  • one
    on duplicate update - splash58

1 answer 1

As a friend wrote in the comments - on duplicate update will help you. Namely:

 INSERT INTO `table` (`id`,`a`,`b`,`c`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `a` = ?, `b` = ? `c` = ?; 

This "thing" is triggered if there are matches in the unique key in the fields to be inserted. Also on the first link, look more syntax using VALUES( column ) in the update-part.

Perhaps at some point there will be a situation where you need to insert the value "and if you already have one with such a key, then do nothing", then you will need to use INSERT IGNORE INTO ... instead INSERT IGNORE INTO ...