一、if函数
在mysql中if()函数的用法类似于java中的三目表达式,其用处也比较多,
具体语法如下:
if(expr1,expr2,expr3),如果expr1的值为true,则返回expr2的值,如果expr1的值为false,则返回expr3的值。注意:if函数可以用在任何位置。
例如:
select * ,if(role_id=1,‘管理员’,‘普通用户’) as role from user_p;当role_id为1时,返回管理员,role_id非1返回普通用户。

二、case语句
1、情景一(case函数)
类似于java总的switch-case结构,代码和运行截图如下:
语法:
- case 表达式
- when 值1 then 结果1或语句1(如果是语句,需要加分号)
- when 值2 then 结果2或语句2(如果是语句,需要加分号)
- …
- else 结果n或语句n(如果是语句,需要加分号)
- end 【case】(如果是放在begin end中需要加上case,如果放在select后面不需要)
select *, case role_id when 1 then "管理员" when 2 then "普通用户" else "游客" end as role from user_p;

2、情景二(case搜索函数)
类似于多重if,可以用在任何位置。代码和运行截图如下:
语法:
- case
- when 条件1 then 结果1或语句1(如果是语句,需要加分号)
- when 条件2 then 结果2或语句2(如果是语句,需要加分号)
- …
- else 结果n或语句n(如果是语句,需要加分号)
- end 【case】(如果是放在begin end中需要加上case,如果放在select后面不需要)
select *,case when age <19 then "少年" when age <30 then "青年" when age >30 and age <50 then "中年" else "老年" end "状态" from info;

三、if elseif语句
注意:只能用在begin end中
- 语法:
- if 情况1 then 语句1;
- elseif 情况2 then 语句2;
- …
- else 语句n;
- end if;
#定义分号
delimiter $$
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
create function age_status(age int) returns varchar(20)
begin
declare status varchar(20) default "老年";
if age < 19 then set status ="少年";
elseif age <30 then set status ="青年";
elseif 30<age<50 then set status ="中年";
else set status ="老年";
end if;
return status;
end $$
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#重新定义分号
delimiter ;
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
select age_status(45);

四、循环
delimiter $$
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
create function insertuser(num int) returns varchar(15)
begin
declare i int default(1);
while i<= num do
insert into info(name,sex,classname,age)
values (concat("name",i),concat("sex",i),concat("classname",i),i);
set i=i+1;
end while;
return "success";
end $$
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
delimiter ;
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
select insertuser(5);


总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论