1.  对 sql 查询到的值进行处理,转换成相应的值:

可以使用:  case when then else end

如:

      方式一: select id, userName, (case when role = 0 then "普通员工" when role = 1 then "管理员" end) as level  from  os_users; 

      方式二:select id, userName, (case role  when  0 then "普通员工" when  1 then "管理员" end) as level  from  os_users;

 

2.  mysql 中 case when then else end 讲解

        Case具有两种格式。简单Case函数和Case搜索函数。

       1. 简单Case函数

case 列名
    when   条件值1   then  选择项1
    when   条件值2    then  选项2.......
    else     默认值
     end



案例:

SELECT
CASE job_level    
    WHEN '1' THEN   '1111'    
        WHEN  '2' THEN  '1111'    
        WHEN  '3' THEN  '1111'   
        ELSE 'eee' 
END 
FROM
    employee

        2. Case搜索函数

## 格式

case  
    when  列名= 条件值1   then  选择项1
    when  列名=条件值2    then  选项2.......
    else    默认值 
end


##案例:

SELECT
    STUDENT_NAME,
    (CASE WHEN score < 60 THEN '不及格'
        WHEN score >= 60 AND score < 80 THEN '及格'
        WHEN score >= 80 THEN '优秀'
        ELSE '异常' END) AS REMARK
FROM
    TABLE

注意:如果你想判断score是否null的情况,WHEN score = null THEN '缺席考试',这是一种错误的写法,正确的写法应为:

CASE WHEN score IS NULL THEN '缺席考试' ELSE '正常' END

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐