一般查询用法:
select name '姓名', pass '密码' ,
case (age)#可以忽略不写
when age<18 then '少年'
when age<30 then '青年'
when age<50 then '中年'
else '老年'
end '年龄' #查询起别名
from users;
#################################
select name '姓名', pass '密码' ,
case age
when 1 then '少年'
when 2 then '青年'
when 3 then '中年'
else '老年'
end '年龄'
from users;

image.png
批量更新用法:
update users set name=
case
when id=1 then 'name1'
when id=2 then 'name2'
else 'nameN'
end ,
pass=
case
when id=1 then 'pass1'
when id=2 then 'pass2'
else 'passN'
end
where id in(1,2,3,4,5,6,7,8,9);

image.png
case when:

Paste_Image.png
//mysql 中的 case when 用法
select title,
case disabled
when '0' then '隐藏'
when '1' then '显示'
else '未知' end '状态'
from db_article;
//case when 两种写法等效(then后的select 语句要加上括号)
select case pid
when 1 then( select title from db_admin_node where id =1)
when 2 then( select title from db_admin_node where id =2)
when 3 then( select title from db_admin_node where id =3)
else ' 其它'
end test,id,title,pid from db_admin_node
select case
when pid=1 then( select title from db_admin_node where id =1)
when pid=2 then( select title from db_admin_node where id =2)
when pid=3 then( select title from db_admin_node where id =3)
else '其它'
end test,id,title,pid from db_admin_node

Paste_Image.png
select id,username,email,is_super,status ,case
when username='admin' then '超级管理员'
when email='root@qq.com' then '系统管理员'
when is_super = 2 then '测试管理员'
when status ='0 'then '失效管理员'
else '其它管理员' end '管理员类型' from db_admin_user
case null when 表达式 then 执行结果 end 字段别名 from 数据表
如果这种情况,如果表达式为布尔false,则结果为null,如果表达式为布尔true,则执行结果
select case when 1>0 then 'test' end test from db_admin_user;
IF(a,b,c)
如果 a 是TRUE (不为 0 或 NULL),则 IF()的返回值为b; 否则返回值则为 c, 类似php的 三目运算!
//简单写法:
select *,if(sex=1,'男','女') sex from user;
//多层嵌套写法:
select *,if(sex=0,'女',if(sex=1,'男','保密')) sex from user;
IFNULL(a,b)
如果 a 不为 NULL(没有 0),则 IFNULL() 的返回值为 a; 否则其返回值为 b。 ifnull(a,b)这个函数一般用来替换null值!
select *,ifnull(email,'你还没设置邮箱') e_mail from user;//如果 email 字段为NULL,则用后面设置的值替换

Paste_Image.png
NULLIF(a,b)
select nullif(arg1,arg2) ; //如果 arg1 = arg2 返回 NULL,否則 返回 arg1
网友评论