zoukankan      html  css  js  c++  java
  • SQL if 和 case when查询示例

      在进行带有返回内容的条件查询的时候,if 和 case when 可以很方便的帮助我们查找满足条件的内容。下面看看他们具体的使用方法。

    if 条件的使用

    1 if (condition, exp1, exp2)
    2 -- condition==true: 返回exp1, 否则返回exp2。

    case when条件的使用

    case when 有两种写法:

    搜索方式

    1 case when condition1 then exp1 -- 满足condition1 则 返回 exp1
    2      when condition2 then exp2
    3      ...
    4      else expN
    5      end

    精简方式

    1 case  col    -- 某一字段
    2       when condition1 then exp1 -- 满足condition1 则 返回 exp1
    3       when condition2 then exp2
    4       ...
    5       else expo
    6       end    

    示例 

    1.  给定一个 salary 表,有 m = 男性 和 f = 女性 的值,交换所有的 f 和 m 值(例如,将所有 f 值更改为 m,反之亦然)

    if 条件写法:

    1 update salary set sex = ( if(sex='m', 'f', 'm'));

    case when 写法

    1 update salary
    2      set sex = ( case when sex='m' then 'f'
    3                       when sex='f' then 'm' end);

    2.  有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。其中纵列的 id 是连续递增的,要求改变相邻俩学生的座位。

    转换思路为修改id,id为偶数则-1,为奇数且不是最大值则+1,然后将id升序排列

    if 条件写法:

    1 select
    2     if(mod(id, 2)= 0, id-1, if(id=( select max(id) from seat), id, id+1)) 
    3 as id, student
    4      -- id为偶数则-1,为奇数且不是最大值则+1
    5 from seat
    6 order by id

    case when 写法:

    1 select
    2     case when id%2=0 then id-1 else (
    3          case when id=(select max(id) from seat) then id else id+1 end
    4     ) end
    5 as id, student
    6 from seat order by id;
  • 相关阅读:
    “ODBC驱动程序不支持动态记录集”错误的解决
    Pro *C/C++学习笔记(一)
    探讨全局变量的析构顺序
    指针和数组关系初探
    (转)Visual C++开发工具与调试技巧整理
    对利用Session纪录datagrid模板列中CheckBox的状态的一点改进
    大学老师列传
    重读保尔的意义
    Rich Edit控件的使用
    C++程序员常用工具集
  • 原文地址:https://www.cnblogs.com/dogeLife/p/11288169.html
Copyright © 2011-2022 走看看