5

Follow up to Update multiple rows in 1 column in MySQL.

What is the most efficient query for updating multiple rows in 2 columns?

UPDATE example_table SET variable1 = 12 WHERE id=1;
UPDATE example_table SET variable2 = 'blue' WHERE id=1;

UPDATE example_table SET variable1 = 42 WHERE id=2;
UPDATE example_table SET variable2 = 'red' WHERE id=2;

UPDATE example_table SET variable1 = 32 WHERE id=3;
UPDATE example_table SET variable2 = 'yellow' WHERE id=3;

Using case seems to be the most efficient, but how would I do it with multiple values being set at one time?

Community
  • 1
  • 1
Don P
  • 60,113
  • 114
  • 300
  • 432

4 Answers4

11

If you have a table named categories and say two columns are display_order and title Here is what you will do :

UPDATE categories
SET display_order = CASE id
    WHEN 1 THEN 32
    WHEN 2 THEN 33
    WHEN 3 THEN 34
END,
title = CASE id
    WHEN 1 THEN 'New Title 1'
    WHEN 2 THEN 'New Title 2'
    WHEN 3 THEN 'New Title 3'
END
WHERE id IN (1,2,3)
HalfWebDev
  • 7,022
  • 12
  • 65
  • 103
2

Some not need to put the this Sign on id ' ' eg: 'id' you can leave it blank...like

UPDATE example_table
SET variable1 = (CASE
    WHEN id = 1 THEN 12
Druid
  • 6,423
  • 4
  • 41
  • 56
Vadz
  • 29
  • 1
  • 1
  • 9
2

I think again CASE is the solution. The idea is to use separate CASE statements for each variable. Something like:

UPDATE `example_table`
SET `variable1` = (CASE
    WHEN `id` = 1 THEN 12
    WHEN `id` = 2 THEN 42
    WHEN `id` = 3 THEN 32
    END),
`variable2` = (CASE
    WHEN `id` = 1 THEN 'blue'
    WHEN `id` = 2 THEN 'red'
    WHEN `id` = 3 THEN 'yellow'
    END);

Hope it helps!

Abhay
  • 6,545
  • 2
  • 22
  • 17
0

Something like this could be what you want to do :

UPDATE example_table SET variable1 = 42,variable2 = 'red' WHERE id=2;
aleroot
  • 71,077
  • 30
  • 176
  • 213
  • Thanks Aleroot, but your answer doesn't deal with updating multiple rows, just multiple columns. – Don P Feb 19 '12 at 20:26