mysql的if 和 case when

mysql中的条件语句主要有if 和case when。

首先,一个初始表格:felix_test

1. IF(expr1,expr2,expr3):如果第一个条件为True,则返回第二个参数,否则返回第三个

select if(author='Felix', 'yes', 'no') as AU from felix_test;

2. 用case when实现if

select case author when 'Felix' then 'yes' else 'no' end as AU from felix_test;  #用case when实现if

3. case when 多重判断

select case author    #多重判断
when 'Felix' then 'good'
when 'Tom' then 'top'
when 'Bob' then 'down'
else 'do not know' 
end
as AU 
from felix_test;

4. case when 多重判断,另一种形式

select 
case when author='Felix' then 'good'
when author='Tom' then 'top'
when author='Bob' then 'down'
else 'do not know'
end 
as AU 
from felix_test;

5. ifnull 判断是否为空:假如第一个参数为null,则返回第二个参数;否则直接返回第一个参数的值

select ifnull(author,'yes') from felix_test;

 

注:mysql里面的if和case when语句也是可以嵌套的。

#

参考:

https://www.cnblogs.com/dogeLife/p/11288169.html

https://blog.csdn.net/bingguang1993/article/details/83110557

posted on 2020-04-06 15:53  落日峡谷  阅读(9198)  评论(1编辑  收藏  举报

导航