case表達式:
case when <判斷表達式> then <表達式> when <判斷表達式> then <表達式> when <判斷表達式> then <表達式> ... else <表達式> end
更新語句需要用update語句:
update 表名 set 列名 = 修改后的值 (where <判斷表達式>)
例子:
給定一個 salary 表,如下所示,有 m = 男性 和 f = 女性 的值。交換所有的 f 和 m 值(例如,將所有 f 值更改為 m,反之亦然)。要求只使用一個更新(Update)語句,並且沒有中間的臨時表。(只能寫一個update語句,不能寫select語句)
id | name | sex | salary |
1 | A | m | 2500 |
2 | B | f | 1500 |
3 | C | m | 5500 |
4 | D | f | 500 |
解答:
update salary set sex = (case sex when 'm' then 'f' else 'm' end)