1

I'm looking for a simple upsert (Update/Insert). The tables looks like this

+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  | PRI | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
| email | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+

There is no key here. The idea is to insert if email is different, else update. The Insert on duplicate key in mysql doesn't suit the purpose.

Is there an elegant way to do this?

4
  • So id is a non-unique field? Multiple persons can have the same id? Commented Aug 27, 2012 at 17:13
  • Upsert doesn't make sense without a unique key. How do you determine if a row exists? If it matches on all fields does it already exists or does it only have to match on one or two fields? Commented Aug 27, 2012 at 18:49
  • yeah id is the primary key, updated the schema Commented Aug 27, 2012 at 18:59
  • 1
    Now that you have a unique key you can use the "on duplicate key update" syntax, correct? Commented Aug 27, 2012 at 19:07

2 Answers 2

3

If you cannot add a unique key on the email column, you'll check to see if the record exists first (preferably in a transaction):

SELECT id FROM mytable WHERE email = '[email protected]' FOR UPDATE

then update the record if it exists:

UPDATE mytable SET name = 'my name' WHERE id = ?

otherwise insert it:

INSERT INTO mytable (name, email) VALUES ('my name', '[email protected]')
Sign up to request clarification or add additional context in comments.

1 Comment

is there a way to do this in a single sql statement?
0

what about:

REPLACE INTO table VALUES(1,'hello', '[email protected]');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.