Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL -- Update if exists else insert with two keys

Tags:

sql

php

mysql

I have a table with fields foreign_key_id | value1 | value2, and I want to update value2 if I have a match for foreign_key_id and value1.

If foreign_key_id or value1 do not exist, I want to insert a new row. Is there a better way to do this than having PHP use a select statement and then branching to either an update or insert?

Edit: value2 can be the same value as in the database, so I cannot run and update, see if affected_rows is 0, and run and insert if it is.

like image 276
Anonymous1 Avatar asked May 29 '11 16:05

Anonymous1


1 Answers

Try using an IF EXISTS to determine whether to execute an UPDATE or an INSERT statement. You can do this in one PHP statement/query.

IF EXISTS(SELECT 1 FROM Mytable WHERE foreign_key_id = f1 AND value1 = v1)
BEGIN
    UPDATE Mytable SET value2 = v2
    WHERE foreign_key_id = f1 AND value1 = v1;
END
ELSE
BEGIN
      INSERT INTO Mytable(foreign_key_id,value1,value2)
      VALUES (f1,v1,v2);
END IF;
like image 123
p.campbell Avatar answered Sep 27 '22 19:09

p.campbell