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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With