MySQL流程函数常见用法实例分析
16lz
2021-12-19
本文实例讲述了MySQL流程函数常见用法。分享给大家供大家参考,具体如下:
流程函数是MySQL相对常用的一类函数, 用户可以使用这类函数在一个SQL语句中实现条件选择, 这样能够提高效率.
下面列出了MySQL跟条件有关的流程函数
函数 | 功能 |
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)
IF(expr1,expr2,expr3)函数: 这里认为月薪在2000元以上的职员属于高薪, 用"high'表示; 而2000以下的职员属于低薪, 用'low'来表示.
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)
希望本文所述对大家MySQL数据库计有所帮助。
更多相关文章
- 《Android和PHP最佳实践》官方站
- ES6 变量声明,箭头函数,数组方法,解构赋值,JSON,类与继承,模块化练习
- 箭头函数的基础使用
- Python技巧匿名函数、回调函数和高阶函数
- 浅析android通过jni控制service服务程序的简易流程
- android用户界面之按钮(Button)教程实例汇
- TabHost与RadioGroup结合完成的菜单【带效果图】5个Activity
- Android(安卓)bluetooth介绍(四): a2dp connect流程分析
- Android架构分析之使用自定义硬件抽象层(HAL)模块