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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM