mardi 19 février 2019

MySql. UPDATE if value exists - else INSERT (for not primary and not unique value)

I have my_table with column1 column.
If there are rows with column1='old' I want to update those rows.
Else, I want to insert a new row.

Something like this:

IF(
   (EXISTS(
      SELECT * FROM my_table WHERE column1='old'
       )),
   (UPDATE my_table SET column1='new' WHERE column1='old'),
   (INSERT INTO my_table (column1) VALUES ('new') )
     )

I use MySql so I cannot use IF on the beginning of query.

column1 is not unique and not primary. So I cannot use ON DUPLICATE KEY UPDATE or REPLACE

Aucun commentaire:

Enregistrer un commentaire