MySQL:if和case的使用


#MySQL 笔记


假设这样一个场景:我们需要对查询的结果进行装换。

这里的转换是指,我查到了1,希望展示为已完成,查到了0,希望展示为未完成

可以用 if 或者 case 。

示例1

创建表:

create table test_table (
    status int  -- 0: 未完成,1:已完成
) engine = InnoDB character set = utf8mb4;

插入数据:

insert into test_table(status) values(0);
insert into test_table(status) values(1);

查询方式1:

select if(status=0, '未完成', '已完成') as human_status from test_table;

查询方式2:

select case status 
        when 0 then '未完成'  
        when 1 then '已完成' 
        end as human_status
from test_table;

查询方式3:

select case status 
        when 0 then '未完成'  
        when 1 then '已完成' 
        else '未知'
        end as human_status
from test_table;

查询结果:

+--------------+
| human_status |
+--------------+
| 未完成       |
| 已完成       |
+--------------+

示例2

如果有3个状态呢?

创建表:

create table test_table (
    status int  -- 0: 未完成,1:已完成,2:取消
) engine = InnoDB character set = utf8mb4;

插入数据:

insert into test_table(status) values(0);
insert into test_table(status) values(1);
insert into test_table(status) values(2);
insert into test_table(status) values(2);

查询方式1:

select if(status=0, '未完成', if(status=1, '已完成', '取消')) as human_status from test_table;

查询方式2:

select case status 
        when 0 then '未完成'  
        when 1 then '已完成' 
        when 2 then '取消'
        end as human_status
from test_table;

查询方式3:

select case status 
        when 0 then '未完成'  
        when 1 then '已完成' 
        when 2 then '取消'
        else '未知'
        end as human_status
from test_table;

查询结果:

+--------------+
| human_status |
+--------------+
| 未完成       |
| 已完成       |
| 取消         |
| 取消         |
+--------------+

示例3

上面的if和case是表达式,并非流程控制语句。我们可以自定义一个函数,在函数中使用 if 或者 case 进行流程控制。

创建表:

create table test_table (
    status int  -- 0: 未完成,1:已完成,2:取消
) engine = InnoDB character set = utf8mb4;

插入数据:

insert into test_table(status) values(0);
insert into test_table(status) values(1);
insert into test_table(status) values(2);
insert into test_table(status) values(2);

创建函数:

drop function if exists human_status;
delimiter //

create function human_status(p_status int) returns char(20) charset utf8mb4
begin
    if p_status=0 then 
        return '未完成';
    elseif p_status=1 then 
        return '已完成';
    elseif p_status=2 then 
        return '取消';
    else 
        return '未知';
    end if;
end //

delimiter ;

查询数据:

mysql> select human_status(`status`) from test_table;
+------------------------+
| human_status(`status`) |
+------------------------+
| 未完成                 |
| 已完成                 |
| 取消                   |
| 取消                   |
+------------------------+


( 本文完 )