首页 > 技术文章 > mysql的if 和 case when

caibaotimes 2021-01-02 10:25 原文

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

  1. IF(expr1,expr2,expr3):如果第一个条件为True,则返回第二个参数,否则返回第三个
select if(author='Felix', 'yes', 'no') as AU from test;
  1. 用case when实现if
#用case when实现if

select case author when 'Felix' then 'yes' else 'no' end as AU from test;  
  1. 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 test;
  1. 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 test;
  1. ifnull 判断是否为空:假如第一个参数为null,则返回第二个参数;否则直接返回第一个参数的值
select ifnull(author,'yes') from test;

推荐阅读