Andre
Andre

Reputation: 613

INSERT...ON DUPLICATE KEY UPDATE..... with two key fields

I have a table that has three fields

field_one field_two field_three

I'd like to do an insert/update, but instead of checking if one of the key fields already exists, I need to check if (field_one,field_two) combination is already in the database, if so, then update instead of inserting.

Upvotes: 3

Views: 1231

Answers (3)

Paul Creasey
Paul Creasey

Reputation: 28834

Sound to me like you can use REPLACE INTO or ON DUPLICATE KEY UPDATE as long as there is a unique constraint on the two fields.

MySql doesn't support the MERGE statement, so need either a unique constraint or some external code.

Upvotes: 0

Piskvor left the building
Piskvor left the building

Reputation: 92752

Create unique index your_index_name on yourtable (field_one,field_two) (see docs) and use INSERT...ON DUPLICATE KEY UPDATE.

MySQL will do the rest automagically.

Upvotes: 5

Lucas Moeskops
Lucas Moeskops

Reputation: 5443

Multiple ways to do this. Easiest is probably something like this:

  • Obtain the existing fields
  • Insert all your fields that are not in the existing fields
  • Update the rest

Upvotes: 0

Related Questions