MySQL中CASE的使用

语法说明:
方式一:
CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN result ...] [ELSE result] END 
方式二:

CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END 


使用演示样例:

mysql> select id,name, (gender) as '性别' from t_user;
+----+------------+------+
| id | name       | 性别 |
+----+------------+------+
| 19 | 张三       | 1    |
| 20 | 小红       | 2    |
| 21 | 超级管理员 |      |
+----+------------+------+
3 rows in set (0.00 sec)


mysql> select id,name, (CASE gender WHEN 1 THEN '男' WHEN 2 THEN '女' ELSE '其它' END) as '性别' from t_user;
+----+------------+------+
| id | name       | 性别 |
+----+------------+------+
| 19 | 张三       | 男   |
| 20 | 小红       | 女   |
| 21 | 超级管理员 | 其它 |
+----+------------+------+
3 rows in set (0.00 sec)


mysql> select id,name, (CASE WHEN gender=1 THEN '男' WHEN gender=2 THEN '女' ELSE '其它' END) as '性别' from t_user;
+----+------------+------+
| id | name       | 性别 |
+----+------------+------+
| 19 | 张三       | 男   |
| 20 | 小红       | 女   |
| 21 | 超级管理员 | 其它 |
+----+------------+------+
3 rows in set (0.00 sec)


应用常景:

Eg:在论坛中,不同类型的贴子的type不一样,置顶贴是一直置顶的,而精华贴和普通贴在排序上是一样的,此时就能使用mysql的Case,使在排序时精华贴和普通贴的type是一样的。


原文地址:https://www.cnblogs.com/yxwkf/p/4086006.html