![27e59bc7b34d34f4a0d80acd92806492.png](https://i-blog.csdnimg.cn/blog_migrate/9a752d92d6d71e5fc611a2459491f8e4.jpeg)
在mysql数据库内case when表达式的应用场景还是很多滴,比如给单条记录做个标记啦,给多条记录划分各列表啦之类的。下面我们就来浅谈下这个超级好用的case when表达式平时一般都是如何运用的~
相信大家伙小学的时候老师常常是不给你的考卷打分数而是打标签吧,比如说现在有这么一个成绩表,我们要给成绩划分各等级,60以下打不及格,60-80打及格,80-90打良,90以上打优,我们就能用case when来解决。
![d58c69aa72c3a68dfb764a1fb65c30ca.png](https://i-blog.csdnimg.cn/blog_migrate/4c6bf373fee68d05184443774c256fb5.jpeg)
请看下面这段代码
select *,
case when score<60 then '不及格'
when score>=60 and score<80 then '及格'
when score>=80 and score<90 then '良好'
else '优秀' end as 表现
from sc
![8b893288b24cb758f5eeb0974e1bb880.png](https://i-blog.csdnimg.cn/blog_migrate/7acac2e8c0dde76df220d82d72ade2dc.jpeg)
还有一种写法,比如我们要根据cid来添加一列老师姓名,假如cid为01对应的是张三,02对应的是李四,03对应的是王五,我们就可以简略的写成以下格式:
select *,
case Cid when 01 then '张三'
when 02 and score<80 then '李四'
else '王五' end as 教师姓名
from sc
![90483b76b0e8832b996793b6eaae047d.png](https://i-blog.csdnimg.cn/blog_migrate/04e746d872a5a20337039eb6e04a5828.jpeg)
这是直接将取值列的列名放到case后面,也就是“case+列名+when”格式,避免了第一种后面要多次键入列名的操作,在等号条件表达式的情况下采用这种方法会比较方便。另外case when内能加入算数运算表达式哦,比如看下面这段代码,我就照搬第一段做一个改动吧:
select *,
case when score<60 then score*0.8
when score>=60 and score<80 then score*0.9
when score>=80 and score<90 then score-10
else score+10 end as 调整后分数
from sc
![bf1ccf94802b3e98c9f8cfb35f296124.png](https://i-blog.csdnimg.cn/blog_migrate/07e81dfab3fc090089792f77e7bab44f.jpeg)
是不是挺厉害哒,当然了case when的应用肯定还有很多,本人才疏学浅就只能讲到这里了,希望大家发挥钻研精神,不断学习哈哈哈哈。