LeetCode-SQL-five
本文中主要是介绍LeetCode
中关于SQL
的练习题,从易到难,循序渐进。文中会介绍题目和尽可能多的解答方案
627-交换工资
题目
给定一个 salary 表,如下所示,有 m = 男性 和 f = 女性 的值。交换所有的 f 和 m 值(例如,将所有 f 值更改为 m,反之亦然)。要求只使用一个更新(Update)语句,并且没有中间的临时表。
注意,您必只能写一个 Update 语句,请不要编写任何 Select 语句
image
答案
首先需要了解更新语句的基本操作:
update 表名
set 列名=修改后的值;
-- 方法1:自己方案
update salary
set sex=(
case sex when 'm' then 'f'
when 'f' then 'm'
else 'other' end);
-- 方法2:使用case表达式
update salary
set sex=(case sex when 'm' then 'f' else 'm' end);
-- 方法3:使用if语句
update salary set sex = if(sex='m','f','m');
if语句
if(expr1,expr2,expr3)
:
- 如果
expr1
的值为true
,则返回expr2
的值 - 如果
expr1
的值为false
,则返回expr3
的值。
网上看到了一种最牛的做法:直接使用ASCII码进行转换
update salary set sex=char(ascii('m') + ascii('f') - ascii(sex));
网友评论