SQL之case...when...then

测试环境: mysql 8.0.13.

sql中支持分支选择, 用的是case...when...then, 简单点的也有if.
为了方便说明, 测试表user如下(sex列:1->男生,2->女生, 3->未知):
原始数据

mysql> select * from user;
+----+------+------+
| id | name | sex  |
+----+------+------+
|  1 | aa   |    1 |
|  2 | bb   |    2 |
|  3 | cc   |    2 |
|  4 | dd   |    1 |
|  5 | ee   |    2 |
|  6 | ee   |    3 |
+----+------+------+

现在将表格数据以人类习惯的形式展示出来:
简单CASE表达式

select u.name "姓名",
    (case u.sex
        when 1 then '男'
        when 2 then '女'
        else '未知'
    end) "性别"
from user u;

搜索CASE表达式

select u.name "姓名",
    (case
        when u.sex=1 then '男'
        when u.sex=2 then '女'
        else '未知'
    end) "性别"
from user u;

上面两种写法结果一样:

+--------+--------+
| 姓名   | 性别   |
+--------+--------+
| aa     ||
| bb     ||
| cc     ||
| dd     ||
| ee     ||
| ee     | 未知   |
+--------+--------+

当然用IF也能实现上面的效果:

select u.name "姓名",
    if(u.sex=1, '男', if(u.sex=2, '女', '未知')) "性别"
from user u;

如果玩过Excel, 这mysql中的if和excel中的if函数用法完全一样!

再来一个需求, 统计下各性别的人数, 并以友好形式展现, 效果为:

+--------+--------+--------------+
| 男生   | 女生   | 未知性别     |
+--------+--------+--------------+
|      2 |      3 |            1 |
+--------+--------+--------------+

根据"简单CASE"和"搜索CASE", 有两种写法:
简单CASE

select
    sum(case u.sex when 1 then 1 else 0 end) 男生,
    sum(case u.sex when 2 then 1 else 0 end) 女生,
    sum(case when u.sex not in (1, 2) then 1 else 0 end) 未知性别
from user u;

搜索CASE

select
    sum(case when u.sex=1 then 1 else 0 end) 男生,
    sum(case when u.sex=2 then 1 else 0 end) 女生,
    sum(case when u.sex <> 1 and u.sex <> 2 then 1 else 0 end) 未知性别
from user u;

同样的, 也可以用IF实现(在这里, 感觉更清晰一些):

select
    sum(if(u.sex=1, 1, 0)) 男生,
    sum(if(u.sex=2, 1, 0)) 女生,
    sum(if(u.sex<>1 and u.sex <> 2, 1, 0)) 未知性别
from user u;

总结:
case...when...then对多分支展示比较清晰, if对简单的逻辑使用时比较方便.

当然case...when...then还有很多其他的妙用, 欢迎补充指正!

发布了231 篇原创文章 · 获赞 77 · 访问量 52万+

猜你喜欢

转载自blog.csdn.net/butterfly5211314/article/details/87895710