简体   繁体   中英

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.

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.

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.

您总是可以查询数据库中的条目,然后根据您的结果选择更新或插入

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM