在 mysql 中,流程控制函数是指可以控制存储过程(stored procedure)或函数(function)中执行流程的语句。以下是几个常用的流程控制函数:
1.if函数实现if……else……的效果。
# 如果expr1为true,则返回expr2,否则返回expr3if(expr1,expr2,expr3)
可以看出,if函数与三元运算符很像,如:
// 比较最大数 int a=10; int b=5; // 比较 int bignum=a>b?a:b;
即,将if函数的三个参数中,expr1是条件表达式,最终结果是true或false,如果条件成立(true)则返回expr2,如果条件不成立(false)则返回expr3。例:
select if(10>5,10,5) as bignum;
2.ifnull函数同样是实现if……else……的效果,相当于if函数的变种。
# 如果expr1不为null,则返回expr1,否则返回expr2ifnull(expr1,expr2)
即将原本的条件表达式变形为判断expr1是否为null,不为null就是其本身(expr1),为空则是expr2.
select ifnull(null,'不空') as notnull
相当于if函数的
select if(null is null,null,'不空') as notnull
判断expr1是否为空,为空(true)显示expr2,不为空(false)显示expr3
3.case函数case函数有两种不同的效果
switch case
相当于java中的switch case的效果。即switch中的变量表达式的值与case后面的常量比较。
int week=3; switch (week){ case 1: system.out.println("星期一"); break; case 2: system.out.println("星期二"); break; case 3: system.out.println("星期三"); break; case 4: system.out.println("星期四"); break; case 5: system.out.println("星期五"); break; case 6: system.out.println("星期六"); break; case 7: system.out.println("星期日"); break; default: system.out.println("非法数据"); break; }
用sql表示:
# now()函数用于获取当前日期和时间,# weekday(date)函数,表示返回date对应的工作日索引,# 因为索引从0开始,所以加1;也可以不加1,将when的常量改为工作日索引也可select case weekday(now())+1 when 1 then '星期一' when 2 then '星期二' when 3 then '星期三' when 4 then '星期四' when 5 then '星期五' when 6 then '星期六' when 7 then '星期日' else '非法数据'end as `week`;
函数结构
case 要判断的变量(字段)或表达式
when 常量1 then 要显示的值1(或语句1);
when 常量2 then 要显示的值2(或语句2);
.......
else 要显示的值n或语句n;
end
注意:
与java不同,直接写case而不是switch,且没有大括号
when后面直接加常量值,不用写冒号,用的是then
then后面如果是显示的值,不需要加分号;如果then后面加的是语句,就需要加分号。
when……then……语句可以有多个。
默认情况用的是else。
结尾用end
4.多重if类似于java中的多重if判断。
int grade=87; if (grade>=90){ system.out.println("优秀"); }else if (grade>=80){ system.out.println("良好"); }else if (grade>=70){ system.out.println("一般"); }else if (grade>=60){ system.out.println("及格"); }else { system.out.println("不及格"); }
用sql表示:
select id,`name`,chinese, case when chinese>=90 then '优秀' when chinese>=80 then '良好' when chinese>=70 then '一般' when chinese>=60 then '及格' else '不及格' end as `rank`from student
函数结构:
case
when 条件1 then 要显示的值1或语句1;
when 条件2 then 要显示的值2或语句2;
......
else 要显示的值n或语句n
end
注意:
case后面没有加条件
when后面是条件,结果是true或false;满足条件执行then,显示后面的值或语句
同样的then后面如果是显示的值,不需要加分号;如果then后面加的是语句,就需要加分号。
以上就是mysql流程控制函数怎么使用的详细内容。
