LeetCode-SQL-five

作者: 皮皮大 | 来源:发表于2020-02-15 09:35 被阅读0次

    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));
    

    相关文章

      网友评论

        本文标题:LeetCode-SQL-five

        本文链接:https://www.haomeiwen.com/subject/szhefhtx.html