Update two different rows in one line of SQL

二次信任 提交于 2020-01-30 05:50:09

问题


Say I have a table called example as:

[abc] | [def]

--1---|-qwerty-

--2---|-asdf---

What I am wanting to do is update both columns in one SQL query (using only one UPDATE).

UPDATE example SET def = 'foo' where abc = '1'

UPDATE example SET def = 'bar' where abc = '2'

The above is what I am wanting to achieve but in one line of sql (using MySQL). I know you can do this like UPDATE example SET def 'foo', SET def = 'bar' but I'm not sure how you can do this with two different where statements.


回答1:


You can execute one UPDATE with the use of IF (which mysql supports) or by using CASE to make it more RDBMS friendly.

UPDATE  example
SET     def = IF(abc = 1, 'foo', 'bar')
WHERE   abc IN (1, 2) -- reason to make it more faster, doesn't go on all records

OR

UPDATE  example
SET     def = CASE WHEN abc = 1 THEN 'foo' ELSE 'bar' END
WHERE abc IN (1, 2) -- reason to make it more faster, doesn't go on all records



回答2:


Like so:

UPDATE example SET def = 
    CASE abc 
        WHEN '1' THEN 'foo' 
        WHEN '2' THEN 'bar'
    END

This allows you to enter more than 2 cases.



来源:https://stackoverflow.com/questions/15503562/update-two-different-rows-in-one-line-of-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!