天天看點

MySQL中CASE表達式的使用前言搜尋 CASE 表達式簡單 CASE 表達式總結

MySQL 中 CASE 表達式的使用

  • 前言
  • 搜尋 CASE 表達式
  • 簡單 CASE 表達式
  • 總結

前言

在 MySQL 中,CASE 表達式相當于程式設計中的一個條件判斷的函數,是 SQL 語言分情況讨論的一種表達形式。

CASE 表達式有兩種:一種是類似程式設計語言的 SWITCH CASE 。 SQL 中稱為簡單 CASE 表達式;

一種是類似于 IF 語句的根據條件表達式進行判斷。 SQL 語言稱為搜尋 CASE 表達式。

搜尋 CASE 表達式

case
when <判斷表達式> then <表達式>
when <判斷表達式> then <表達式>
…
else <表達式>
end
           

從上而下根據條件進行判斷,滿足的話就進入 then 之後的表達式中,不滿足的話就進入 else 。else 可省略,省略後預設為 null 值。end 不能省略。

例子:

select e.id,e.name,e.dept_id,
( case when e.sex="1" then "男"
	when e.sex="2" then "女" 
	when e.sex is null then "空"
	else "其它" end ) 性别
from t_employee e
           

原表:

MySQL中CASE表達式的使用前言搜尋 CASE 表達式簡單 CASE 表達式總結

查詢結果:

MySQL中CASE表達式的使用前言搜尋 CASE 表達式簡單 CASE 表達式總結

例子:

select e.id,e.name,e.sex,e.dept_id,
( case when e.sex=1 then 1 end ) "男",
( case when e.sex=2 then 0 end ) "女"
from t_employee e 
           

查詢結果:

MySQL中CASE表達式的使用前言搜尋 CASE 表達式簡單 CASE 表達式總結

簡單 CASE 表達式

case value
when <判斷值> then <表達式>
when <判斷值> then <表達式>
…
else <表達式>
end
           

根據 value 與判斷值進行比較。滿足的話就進入 then 之後的表達式中,不滿足的話就進入 else 。else 可省略,省略後預設為 null 值。end 不能省略。

例子:

select e.id,e.name,e.sex,e.dept_id,
( case e.sex
when "1" then "男"
when "2" then "女"
else "其他" end ) 性别
from t_employee e
           

查詢結果:

MySQL中CASE表達式的使用前言搜尋 CASE 表達式簡單 CASE 表達式總結

總結

如果這篇部落格對你有幫助的話,記得給我點個贊,你的鼓勵是對我最大的支援!謝謝。◕‿◕。