search

Home  >  Q&A  >  body text

Multiple updates in MySQL

I know you can insert multiple rows at once, is there a way to update multiple rows at once (like in one query) in MySQL?

edit: For example I have the following

Name   id  Col1  Col2
Row1   1    6     1
Row2   2    2     3
Row3   3    9     5
Row4   4    16    8

I want to combine all the following updates into one query

UPDATE table SET Col1 = 1 WHERE id = 1;
UPDATE table SET Col1 = 2 WHERE id = 2;
UPDATE table SET Col2 = 3 WHERE id = 3;
UPDATE table SET Col1 = 10 WHERE id = 4;
UPDATE table SET Col2 = 12 WHERE id = 4;

P粉154798196P粉154798196241 days ago518

reply all(2)I'll reply

  • P粉404539732

    P粉4045397322024-03-26 14:07:25

    Since you have dynamic values, you need to use IF or CASE to update the column. It gets a little ugly, but it should work.

    Using your example, you could do this:

    UPDATE table SET Col1 = CASE id 
                              WHEN 1 THEN 1 
                              WHEN 2 THEN 2 
                              WHEN 4 THEN 10 
                              ELSE Col1 
                            END, 
                     Col2 = CASE id 
                              WHEN 3 THEN 3 
                              WHEN 4 THEN 12 
                              ELSE Col2 
                            END
                 WHERE id IN (1, 2, 3, 4);
    

    reply
    0
  • P粉536909186

    P粉5369091862024-03-26 11:21:09

    Yes, it is possible - you can use INSERT ... ON DUPLICATE KEY UPDATE.

    Use your example:

    INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12)
    ON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2);

    reply
    0
  • Cancelreply