48
$query = mysql_query("UPDATE a SET fruit = '**apple**' WHERE id = '**1**' ");
$query2 = mysql_query("UPDATE a SET fruit = '**orange**' WHERE id = '**2**' ");
$query3 = mysql_query("UPDATE a SET fruit = '**peach**' WHERE id = '**3**' ");

is there any way to simplify it to one query?

2
  • you have value for fruit and id are in array?? Commented Jul 26, 2012 at 7:50
  • i want to say that the value of the fruit and id how you can get?? Commented Jul 26, 2012 at 7:50

4 Answers 4

68

I found a following solution:

INSERT into `table` (id,fruit)
    VALUES (1,'apple'), (2,'orange'), (3,'peach')
    ON DUPLICATE KEY UPDATE fruit = VALUES(fruit);

Id must be unique or primary key. But don't know about performance.

Sign up to request clarification or add additional context in comments.

3 Comments

This works for me. I wonder why mysql did not implement a bulk update statement.
Ideal solution for some use cases, but this will not work if table has a required column b which has no default value, even if the records which are being updated have already defined this value. Updating only parts of an existing record requires a different approach.
Should be aware that this way auto_increment still grows for each unsuccessful insert statement attempt
66

Yes you can do it using this query:

UPDATE a 
SET fruit = (CASE id WHEN 1 THEN 'apple'
                     WHEN 2 THEN 'orange'
                     WHEN 3 THEN 'peach'
             END)
WHERE id IN(1,2 ,3);

2 Comments

case id when 1 then 'apple' when 2 then ... is an alternative.
I just wanted to mention an observation that the CASE statement will test each and every case until a condition is satisfied. When id is 3, 1 and 2 will be tested before being true. For that reason alone I went with @Yaroslav's approach where the condition of a duplicate key sets the value without further conditionals applied.
3

Based on the warning message

'VALUES function' is deprecated and will be removed in a future release. Please use an alias (INSERT INTO ... VALUES (...) AS alias) and replace VALUES(col) in the ON DUPLICATE KEY UPDATE clause with alias.col instead

One may consider a slight modification of Yaroslav's solution like so:

INSERT into `table` (id,fruit)
VALUES (1,'apple'), (2,'orange'), (3,'peach') as tb
ON DUPLICATE KEY UPDATE fruit = tb.fruit;

It does just the same thing but mutes the warning message.

Comments

2

Using IF() function in MySQL this can be achieved as

UPDATE a
SET fruit = IF (id = 1, 'apple', IF (id = 2, 'orange', IF (id = 3, 'peach', fruit)));

3 Comments

this is a pretty old question... :-)
but fresh answer ;-)
@skumar your answer received less upvote than your comment. Cool

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.