Multiple Updates in MySQL

前端 未结 17 1309
南方客
南方客 2020-11-22 01:31

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

Edit: For example I have the followi

17条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 01:31

    Since you have dynamic values, you need to use an IF or CASE for the columns to be updated. It gets kinda ugly, but it should work.

    Using your example, you could do it like:

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

提交回复
热议问题