-2

I have a MySQL table like this.

Table/Animals

Id-Publish-Update-Name
1--17:00---01:00--Dog
2--18:00---01:00--Cat
3--19:00---03:00--Penguin

Add a "Penguin". I did it.

INSERT INTO Animals (Name) VALUES ('Penguin')

Next I want to do is "add Penguin". However, if "Penguin" already exists, update only "Update", do not add new column.

Dharman
  • 30,962
  • 25
  • 85
  • 135
saya-ma
  • 33
  • 2

2 Answers2

3

MySQL supports on duplicate key update:

insert into animals (publish, update, name)
    values (?, ?, ?)
    on duplicate key update publish = values(publish), update = values(update);

For this to work, you need a unique index or constraint on name:

create unique index unq_animals_name on animals(name);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

To perform an "upsert" (update or insert) you use the MERGE command.

Eldar S
  • 579
  • 3
  • 17