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
对于所有大于 1
的 student_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"
。
相关用法
- MySQL CASE()用法及代码示例
- MySQL CAST()用法及代码示例
- MySQL CURTIME()用法及代码示例
- MySQL Convert()用法及代码示例
- MySQL CONCAT()用法及代码示例
- MySQL CEIL方法用法及代码示例
- MySQL CHARACTER_LENGTH()用法及代码示例
- MySQL CEILING()用法及代码示例
- MySQL CONCAT方法用法及代码示例
- MySQL CURRENT_TIME()用法及代码示例
- MySQL CONV( )用法及代码示例
- MySQL CHAR_LENGTH()用法及代码示例
- MySQL CHAR and VARCHAR用法及代码示例
- MySQL CONVERT_TZ方法用法及代码示例
- MySQL COUNT()用法及代码示例
- MySQL CONVERT_TZ()用法及代码示例
- MySQL CONCAT_WS方法用法及代码示例
- MySQL CURDATE方法用法及代码示例
- MySQL CONVERT( )用法及代码示例
- MySQL COT()用法及代码示例
- MySQL CURRENT_TIME方法用法及代码示例
- MySQL COMPRESS( )用法及代码示例
- MySQL Count()用法及代码示例
- MySQL CONNECTION_ID( )用法及代码示例
- MySQL CURTIME方法用法及代码示例
注:本文由纯净天空筛选整理自Arthur Yanagisawa大神的英文原创作品 MySQL | CASE。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。