case [expr] when [value1] then [result1]...else[default] end,如果expr等于value1,返回result1,否则返回default。
create table salary (userid int, salary decimal(8,2));insert into salary values(1, 1000), (2, 2000), (3, 3000), (4, 4000);insert into salary values(5, null);select * from salary;+--------+---------+| userid | salary |+--------+---------+| 1 | 1000.00 || 2 | 2000.00 || 3 | 3000.00 || 4 | 4000.00 || 5 | NULL |+--------+---------+select if(salary > 2000, 'high', 'low') from salary;+----------------------------------+| if(salary > 2000, 'high', 'low') |+----------------------------------+| low || low || high || high || low |+----------------------------------+select ifnull(salary, 0) from salary;+-------------------+| ifnull(salary, 0) |+-------------------+| 1000.00 || 2000.00 || 3000.00 || 4000.00 || 0.00 |+-------------------+select userid, case when salary<=2000 then 'low' when salary=3000 then 'mid' else 'high' end as salary_level from salary;+--------+--------------+| userid | salary_level |+--------+--------------+| 1 | low || 2 | low || 3 | mid || 4 | high || 5 | high |+--------+--------------+select userid, case salary when 1000 then 'low' when 2000 then 'low' when 3000 then 'mid'when 4000 then 'high' end as salary_level from salary;+--------+--------------+| userid | salary_level |+--------+--------------+| 1 | low || 2 | low || 3 | mid || 4 | high || 5 | NULL |+--------+--------------+