您好,欢迎访问一九零五行业门户网

mysql case...when语句的几个用法_MySQL

bitscn.com
mysql case...when语句的几个用法
一般情况下,case ...when都用在select语句中,不过可以在其他子句中使用 
1 在order by子句中进行自定义排序 
sql代码  
show create table 20130225t1;  
create table `20130225t1` (  
  `id` tinyint(4) not null auto_increment,  
  `b` char(1) not null,  
  primary key (`id`)  
) engine=innodb
select * from  20130225t1; 
1 甲 
2 丁 
3 乙 
4 丙 
现在想b字段按照甲乙丙丁的顺序排序,直接order by b是不能实现的,正统的做
法可以加一个排序用的字段,按照该字段排序. 
不过可以用case when语句实现 
sql代码  
select * from  20130225t1   
order by case b when '甲' then 1 when '乙' then 2   
when '丙' then 3 when '丁' then 4 end
1 甲 
3 乙 
4 丙 
2 丁
还有个手段是find_in_set 函数 
sql代码  
select * from  20130225t1   
order by find_in_set(b,'甲,乙,丙,丁')
1 甲 
3 乙 
4 丙 
2 丁
2在where子句中用来进行条件查询 
考虑以下两张表 
sql代码  
show create table 20130225work  
create table `20130225work` (  
  `id` tinyint(4) not null auto_increment,  
  `role_id` tinyint(4) not null,  
  `dep_id` tinyint(4) not null,  
  primary key (`id`)  
) engine=innodb
sql代码  
show create table 20130225role  
create table `20130225role` (  
  `id` tinyint(4) not null,  
  `role_name` varchar(5) default null,  
  primary key (`id`)  
) engine=innodb
20130225work是各部门提交上来的申请,role_id是能够看到申请的角色的id,dep_id是提交申请的部门 
20130225role是角色.
select * from  20130225role
1 部门经理 
2 总经理
select * from  20130225work 
1 1 1 
2 1 2 
3 2 1 
4 2 2
现在问题是部门经理角色只能看到自己部门的申请,总经理看到所有部门的申请.
(1)可以在20130225work中加个字段need_check,1表示该申请需要检查部门,0表示不需要
现在要根据role id和dep_id查找该角色对应的申请 
sql代码  
set @role_id=1;  
set @dept_id=1;  
select * from  20130225work  
where role_id=@role_id and (case need_check   
            when 1 then dep_id=@dept_id  
            else 1=1  
                end)
1 1 1 1
sql代码  
set @role_id=2;  
set @dept_id=1;  
select * from  20130225work  
where role_id=@role_id and (case need_check   
                    when 1 then dep_id=@dept_id  
                    else 1=1  
                end)
3 2 1 0 
4 2 2 0
(2)或者把need_check加到20130225role中 
sql代码  
set @role_id=1;  
set @dept_id=2;  
select * from  20130225work w,20130225role r  
where r.id=@role_id and w.role_id=r.id  
                and (case need_check   
                    when 1 then dep_id=@dept_id  
                    else 1=1  
                end)
case when也能在group by语句中出现,只是不知道能有啥作用. 
其实我最希望它能出现在from语句中,就能动态指定from的表.
bitscn.com
其它类似信息

推荐信息