CASE When的用法

一、case when主要用来转换显示

1.1、用法一case when搜索函数

数据库查询结果是woman和man,转为男和女

SELECT
CASE WHEN SEX = 'WOMAN' THEN '女' 
	 WHEN SEX = 'MAN' THEN '男' END 
FROM
	 T_SYS_USER
	 
注:给转换后的列起别名:
	CASE WHEN SEX = 'WOMAN' THEN '女' 
	 WHEN SEX = 'MAN' THEN '男' END as 性别

结果展示: CASE When的用法_第1张图片

1.2 case的简单函数

简单函数形式:case 列名 when ‘条件’ then ‘显示结果’

SELECT
CASE SEX WHEN 'WOMAN' THEN '女' 
		 WHEN 'MAN' THEN '男' 
		 ELSE '其他' END as 性别
FROM
		T_SYS_USER 
1.3 case when放在where后面需要注意的情况

在where后面这样使用将会报错:

select * 
from t1, t2
where t2.name in
CASE
    when t1.id = 0 then ('aaa', 'bbb')
    when t1.id = 1 then ('bbb', 'ccc')
    when t1.id = 2 then ('ccc', 'ddd')
END

正确写法:

select * 
from t1, t2
where t2.name in
CASE
    when t1.id = 0 then B.name in ('aaa', 'bbb')
    when t1.id = 1 then B.name in ('bbb', 'ccc')
    when t1.id = 2 then B.name in ('ccc', 'ddd')
END

加深对case when和where的理解:case when放置到where后面

你可能感兴趣的:(数据库,小雷学习笔记,数据库)