开发者

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

开发者 https://www.devze.com 2023-03-31 18:00 出处:网络
I have a MySQL query that looks like this: UPDATE `Table` SET `Column` = CASE WHEN `Option Id` = \'1\' THEN \'Apple\'

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
  开发者_Python百科   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.


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.


Of course it does not insert. As there is no such value, it cannot get updated.

I suppose you are normalizing a database by putting in the values already present and now want to add the required mapping for every valid value.

So it would be better to start from scratch and just do INSERTs.


You could always query the database for entries and then choose update or insert based on yor results


I see no point in such updating.
Why don't you have a separate table with option ids and corresponding values, leaving only option ids linked to user ids in this one?

0

精彩评论

暂无评论...
验证码 换一张
取 消