mysql中的if使用总结

来源:互联网 发布:网络剧的受众分析 编辑:程序博客网 时间:2024/06/06 01:23

Mysql的if表达式 if(expr1,expr2,expr3)

如果 expr1 是true (expr1 !=  0 and expr1 != NULL),则 if 的返回值为expr2; 否则返回值则为 expr3。if() 的返回值为数字值或字符串值,具体情况视其所在语境而定。


select if(sex = 1,"男","女") as sexStr from user where userid =1;select if(now() > end_time,2,if(now() > start_time and now() < end_time,0,1)) `status` from user where id =1;select if(start_time is null, create_time,start_time)  startTime from user where id =1;


ifnull(expr1,expr2) 假如expr1 不为 NULL,则 ifnull() 的返回值为 expr1; 否则其返回值为 expr2。ifnull()的返回值是数字或是字符串,具体情况取决于其所使用的语境。

select ifnull(start_time, create_time) time  from user where id =1;
mysql> SELECT IFNULL(1,0);        -> 1mysql> SELECT IFNULL(NULL,10);        -> 10mysql> SELECT IFNULL(1/0,10);        -> 10mysql> SELECT IFNULL(1/0,'yes');        -> 'yes'

ifnull(expr1,expr2) 的默认结果值为两个表达式中更加“通用”的一个,顺序为STRING、 REAL或 INTEGER。


IF ELSE 做为流程控制语句使用

if实现条件判断,满足不同条件执行不同的操作

IF search_condition THEN     statement_list  [ELSEIF search_condition THEN]      statement_list ...  [ELSE     statement_list]  END IF 

当IF中条件search_condition成立时,执行THEN后的statement_list语句,否则判断ELSEIF中的条件,成立则执行其后的statement_list语句,否则继续判断其他分支。当所有分支的条件均不成立时,执行ELSE分支。search_condition是一个条件表达式,可以由“=、<、<=、>、>=、!=”等条件运算符组成,并且可以使用AND、OR、NOT对多个表达式进行组合。

例如,建立一个存储过程,该存储过程通过学生学号(student_no)和课程编号(course_no)查询其成绩(grade),返回成绩和成绩的等级,成绩大于90分的为A级,小于90分大于等于80分的为B级,小于80分大于等于70分的为C级,依次到E级。那么,创建存储过程的代码如下:


create procedure dbname.proc_getGrade (stu_no varchar(20),cour_no varchar(10))  BEGIN declare stu_grade float;  select grade into stu_grade from grade where student_no=stu_no and course_no=cour_no;  if stu_grade>=90 then     select stu_grade,'A';  elseif stu_grade<90 and stu_grade>=80 then     select stu_grade,'B';  elseif stu_grade<80 and stu_grade>=70 then     select stu_grade,'C';  elseif stu_grade70 and stu_grade>=60 then     select stu_grade,'D';  else     select stu_grade,'E';  end if;  END 

注意:if作为一条语句,在END IF后需要加上分号“;”以表示语句结束,其他语句如CASE、LOOP等也是相同的。


0 0
原创粉丝点击