Home » Php » How to bulk update mysql data with one query?

How to bulk update mysql data with one query?

Posted by: admin November 29, 2017 Leave a comment

Questions:
$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?

Answers:

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);

Questions:
Answers:

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.

Questions:
Answers:

Yes,You can achieve this by executing this;
Hope it works.

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);

Questions:
Answers:

Please refer to
http://blog.bubble.ro/how-to-make-multiple-updates-using-a-single-query-in-mysql/

correct answer is

UPDATE a 
SET fruit = (CASE id WHEN 1 THEN 'apple'
                     WHEN 2 THEN 'orange'
                     WHEN 3 THEN 'peach'
                     ELSE fruit
             END)

 WHERE id IN(1,2 ,3);