MySQL — Update if exists else insert with two keys

后端 未结 4 673
栀梦
栀梦 2021-01-03 03:17

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 value

相关标签:
4条回答
  • 2021-01-03 03:23

    Yes, you can just run the update, then get the number of affected rows. If this is 0, run the insert. That will save you a select, because it is included in the update.

    [edit]

    Query as posted in the comments. Insert using select. This will save an select upfront. You can use mysql_affected_rows to get the number of rows inserted. If it returns 0, you can update. It actually contains the select, so I'm not sure if it is fasters (mysql and subselects aren't exactly friends). It will save you a roundtrip to the database however, and that might just make up for that.

    insert into yourtable(f1, f2, fr) 
    select 'value1', 'value2', 'value3' 
    from dual /* yeah, I'm an Oracle dude */
    where 
      not exists (
          select 'x' 
          from yourtable 
          where f1 = 'value1' and f2 = 'value2')
    
    0 讨论(0)
  • 2021-01-03 03:35

    Best option: Use REPLACE instead of INSERT or UPDATE. It depends on the use of a primary key or unique key.

    0 讨论(0)
  • 2021-01-03 03:42

    Try this slight modification if you cannot get p.campbell's solution to work

    IF EXISTS(SELECT 1 FROM Mytable WHERE foreign_key_id = f1 AND value1 = v1) THEN
        UPDATE Mytable SET value2 = v2
        WHERE foreign_key_id = f1 AND value1 = v1;
    ELSE
        INSERT INTO Mytable(foreign_key_id,value1,value2)
        VALUES (f1,v1,v2);
    END IF;
    
    0 讨论(0)
  • 2021-01-03 03:46

    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;
    
    0 讨论(0)
提交回复
热议问题