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

一般情况下,case ...when都用在select语句中,不过可以在其他子句中使用
1 在order by子句中进行自定义排序
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语句实现
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 函数
select * from  20130225t1 
order by FIND_IN_SET(b,'甲,乙,丙,丁')

1 甲
3 乙
4 丙
2 丁

2在where子句中用来进行条件查询
考虑以下两张表
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


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查找该角色对应的申请
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

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中

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的表.

猜你喜欢

转载自kabike.iteye.com/blog/1814850