Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql UNION for UPDATE

Tags:

mysql

union

Is there a way to update multiple rows with different values for each row using a single SQL query? I have to update one colum in many rows with different data. Using individual update queries for each row seems excessive so if it's possible I would like to consolidate this process into a single SQL statement or at least reduce the number of queries required.

I am using PHP with the Zend framework and MySql.

like image 707
user63371 Avatar asked Jan 23 '23 20:01

user63371


2 Answers

Create a temporary table and fill it with:

CREATE TEMPORARY TABLE temptable (id INTEGER, VALUE VARCHAR(200))

INSERT
INTO temptable
VALUES
  ('1', 'val1'),
  ('2', 'val2'),
  ('3', 'val3'),
  ('4', 'val4')

Then issue:

UPDATE
  mytable m, temptable t
SET m.value = t.value
WHERE m.id = t.id
like image 94
Quassnoi Avatar answered Feb 12 '23 12:02

Quassnoi


Don't know about MySQL specifically, but to update multiple rows based on a SELECT, or a UNION of multiple SELECTs, I would do

UPDATE U
SET MyColumn = T.OtherColumn
FROM MyUpdateTable AS U
     JOIN
     (
         SELECT [OtherColumn] = OtherColumn1
         FROM MyOtherTable1
         WHERE ...
         UNION
         SELECT OtherColumn2
         FROM MyOtherTable2
         WHERE ...
     ) AS T
         ON T.ID = U.ID

Update 10/28/2014, converted to work for MySQL:

UPDATE MyUpdateTable AS U
    JOIN
    (
        SELECT [OtherColumn] = OtherColumn1
        FROM MyOtherTable1
        WHERE ...
        UNION
        SELECT OtherColumn2
        FROM MyOtherTable2
        WHERE ...
    ) AS T
        ON T.ID = U.ID
        SET MyColumn = T.OtherColumn
like image 36
Kristen Avatar answered Feb 12 '23 12:02

Kristen