nsi*_*lva 3 mysql sql sql-update
假设我有一个名为example的表:
[abc] | [DEF]
--1 --- | -qwerty-
--2 --- | -asdf ---
我想要做的是在一个SQL查询中更新两列(仅使用一个UPDATE).
UPDATE example SET def = 'foo' where abc = '1'
UPDATE example SET def = 'bar' where abc = '2'
Run Code Online (Sandbox Code Playgroud)
以上是我想要实现但在一行sql(使用MySQL).我知道你可以这样做,UPDATE example SET def 'foo', SET def = 'bar'但我不知道你怎么能用两个不同的where语句做到这一点.
您可以UPDATE使用IF(支持mysql)或使用CASE它来使RDBMS更友好.
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
Run Code Online (Sandbox Code Playgroud)
要么
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
653 次 |
| 最近记录: |