当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。