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
    – absessive
    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]')
1
  • 3
    is there a way to do this in a single sql statement?
    – absessive
    Commented Aug 27, 2012 at 18:55
0

what about:

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.