Bulk update mysql with where statement

user3673384 picture user3673384 · Mar 1, 2016 · Viewed 61.9k times · Source

How to update mysql data in bulk ? How to define something like this :

UPDATE `table` 
WHERE `column1` = somevalues
SET  `column2` = othervalues

with somevalues like :

VALUES
    ('160009'),
    ('160010'),
    ('160011');

and othervalues :

VALUES
    ('val1'),
    ('val2'),
    ('val3');

maybe it's impossible with mysql ? a php script ?

Answer

Farside picture Farside · Mar 1, 2016

The easiest solution in your case is to use ON DUPLICATE KEY UPDATE construction. It works really fast, and does the job in easy way.

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

or to use CASE construction

UPDATE table
SET column2 = (CASE column1 WHEN 1 THEN 'val1'
                 WHEN 2 THEN 'val2'
                 WHEN 3 THEN 'val3'
         END)
WHERE column1 IN(1, 2 ,3);