流程函数是MySQL相对常用的一类函数, 用户可以使用这类函数在一个SQL语句中实现条件选择, 这样能够提高效率.
函数 | 功能 |
IF(expr1,expr2,expr3) | 如果expr1是真, 返回expr2, 否则返回expr3 |
IFNULL(expr1,expr2) | 如果expr1不是NULL,返回expr1,否则返回expr2 |
CASE WHEN [value1] THEN[result1]… ELSE[default] END | 如果value是真, 返回result1,否则返回default |
CASE [expr] WHEN [value1] THEN[result1]… ELSE[default] END | 如果expr等于value1, 返回result1,否则返回default |
create table salary(userid int, salary decimal(9,2));
insert into salary values (1,1000),(2,2000),(3,3000),(4,4000),(5,5000),(1,null);
mysql> select * from salary; +--------+---------+ | userid | salary | +--------+---------+ | 1 | 1000.00 | | 2 | 2000.00 | | 3 | 3000.00 | | 4 | 4000.00 | | 5 | 5000.00 | | 1 | NULL | +--------+---------+ 6 rows in set (0.00 sec)
mysql> select if(salary>2000, ‘high‘, ‘low‘) from salary; +--------------------------------+ | if(salary>2000, ‘high‘, ‘low‘) | +--------------------------------+ | low | | low | | high | | high | | high | | low | +--------------------------------+ 6 rows in set (0.00 sec)
mysql> select ifnull(salary,0) from salary; +------------------+ | ifnull(salary,0) | +------------------+ | 1000.00 | | 2000.00 | | 3000.00 | | 4000.00 | | 5000.00 | | 0.00 | +------------------+ 6 rows in set (0.00 sec)
mysql> select CASE WHEN salary<=2000 THEN ‘low‘ else ‘high‘ END from salary; +---------------------------------------------------+ | CASE WHEN salary<=2000 THEN ‘low‘ else ‘high‘ END | +---------------------------------------------------+ | low | | low | | high | | high | | high | | high | +---------------------------------------------------+ 6 rows in set (0.00 sec)
mysql> select CASE salary WHEN 1000 THEN ‘low‘ when 2000 THEN ‘mid‘ ELSE ‘high‘ END from salary; +-----------------------------------------------------------------------+ | CASE salary WHEN 1000 THEN ‘low‘ when 2000 THEN ‘mid‘ ELSE ‘high‘ END | +-----------------------------------------------------------------------+ | low | | mid | | high | | high | | high | | high | +-----------------------------------------------------------------------+ 6 rows in set (0.00 sec)
原文:http://www.cnblogs.com/chenqionghe/p/4838412.html