Search code examples
phpmysqlcaseinsert-update

How can I insert a row if it doesn't already exist while updating multiple rows?


I have a MySQL query that looks like this:

UPDATE `Table` SET `Column` = 
    CASE 
      WHEN `Option Id` = '1' THEN 'Apple'
      WHEN `Option Id` = '2' THEN 'Banana'
      WHEN `Option Id` = '3' THEN 'Q-Tip'
    END 

An my table currently looks like this:

Option Id | Column
        1 |      x
        2 |      x

I'd like it to result in:

Option Id | Column
        1 |  Apple
        2 | Banana
        3 |  Q-Tip

But it doesn't insert the Q-Tip row. I've looked up and read a bit about INSERT ON DUPLICATE KEY UPDATE and REPLACE, but I can't find a way to get those to work with this multiple row update using CASE. Do I have to write a separate query for each row to get this to work, or is there a nice way to do this in MySQL?

Option Id is not a Key itself, but it is part of the Primary Key.

EDIT Some more info:

I'm programming in PHP, and essentially I'm storing an array for the user. Option Id is the key, and Column is the value. So for simplicities sake, my table could look like:

User Id | Option Id | Value
     10 |         1 | Apple
     10 |         2 |  Shoe
     11 |         1 |  Czar
...

That user can easily update the elements in the array and add new ones, then POST the array to the server, in which case I'd like to store it in the table. My query above updates any array elements that they've edited, but it doesn't insert the new ones. I'm wondering if there is a query that can take my array from POST and insert it into the table without me having to write a loop and have a query for every array element.


Solution

  • This should work, if Option_Id is a primary key:

    REPLACE INTO `Table` (`Option_Id`, `Column`) VALUES
    (1, 'Apple'),
    (2, 'Banana'),
    (3, 'Q-Tip');
    

    The statement means: Insert the given rows or replace the values, if the PK is already existing.