627. 变更性别

题目描述:
  给定一个 salary 表,如下所示,有 m = 男性 和 f = 女性 的值。交换所有的 f 和 m 值(例如,将所有 f 值更改为 m,反之亦然)。要求只使用一个更新(Update)语句,并且没有中间的临时表。

注意,您必只能写一个 Update 语句,请不要编写任何 Select 语句。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-salary

解法一:case 用法

  语法:

case when <判断表达式> then <表达式> 
     when <判断表达式> then <表达式> 
     ...
     else <表达式>
end

  答案1:

update salary set 
sex = case sex when 'm' then 'f'
               else 'm'
end;

  答案2:

update salary set 
sex = case when sex='m' then 'f'
           else 'm'
end;

在这里插入图片描述

解法二:ASCII 转换

update salary set 
sex = char(ascii('m') + ascii('f') - ascii(sex));

在这里插入图片描述

题解三:IF

update salary set sex = IF(sex = 'm', 'f', 'm')

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40395874/article/details/115115160
627