當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


MySQL CASE用法及代碼示例

MySQL 的 CASE 運算符允許我們向查詢添加多個條件,並返回滿足的第一個條件的值。

用法

-- Syntax 1: Return result for first comparison of value = compare_value that is true
SELECT column(s),
CASE value
 WHEN compare_value THEN result1
 WHEN compare_value2 THEN result2
 ELSE result3
END
FROM table;
-- Syntax 2: Return result for first condition that is true
SELECT column(s),
CASE
 WHEN condition1 THEN result1
 WHEN condition2 THEN result2
 ELSE result3
END
FROM table;
注意

在這兩種情況下,如果沒有比較/條件為 true,則返回 ELSE 之後的結果,如果沒有 ELSE 部分,則返回 NULL

例子

請考慮下表有關學生的課外活動:

student_id

俱樂部

date_entered

1

Football

2016-02-13

2

Boxing

2016-05-25

3

Apple

2018-08-17

4

Fishing

2017-01-01

5

NULL

NULL

可以使用此處的代碼創建上述示例表。

語法1

檢查student_id是否為1並根據比較結果返回一個字符串:

SELECT student_id,
CASE student_id
 WHEN 1 THEN "student1"
 ELSE "Not student1" 
END 
AS 'Case Outcome'
FROM extracurricular;



+------------+--------------+
| student_id | Case Outcome |
+------------+--------------+
|          1 | student1     |
|          2 | Not student1 |
|          3 | Not student1 |
|          4 | Not student1 |
|          5 | Not student1 |
+------------+--------------+

對於student_id=1,由於比較為真,我們返回"student1"。對於所有其他學生,由於比較為假,我們返回 ELSE 塊返回值 "Not student1"

語法2

對於所有大於 1student_id 返回 "Not student1"

SELECT student_id,
CASE
 WHEN student_id > 1 THEN "Not student1"
 ELSE "student1" 
END
AS 'Case Outcome'
FROM extracurricular;



+------------+--------------+
| student_id | Case Outcome |
+------------+--------------+
|          1 | student1     |
|          2 | Not student1 |
|          3 | Not student1 |
|          4 | Not student1 |
|          5 | Not student1 |
+------------+--------------+

對於student_id=1,因為條件為假,我們返回ELSE塊返回值"student1"。對於所有其他學生,由於條件為真,我們返回 "Not student1"

相關用法


注:本文由純淨天空篩選整理自Arthur Yanagisawa大神的英文原創作品 MySQL | CASE。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。