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;
原文地址:https://www.cnblogs.com/dogeLife/p/11288169.html