Oracle中多个case语句间+运算符的作用是什么?有无替代实现方案?
问题解答
1. +运算符的作用
这里的+是标准算术加法运算符,作用是将多个CASE语句的返回值累加得到单个状态编码值:
- 每个CASE语句对应一个2的幂次返回值(1=2⁰、2=2¹、4=2²),且每个值的二进制位完全不重叠:1对应二进制
001、2对应010、4对应100 - 累加后的最终结果可以直接反推
t1/t2/t3的id非空状态,例如:- 结果为0:三个表的id全为空
- 结果为3(1+2):
t1.id和t2.id非空,t3.id为空 - 结果为5(1+4):
t1.id和t3.id非空,t2.id为空 - 结果为7(1+2+4):三个表的id全为非空
这是Oracle开发中常用的多布尔状态压缩技巧,后续做条件判断时只需比对单个数值,无需写多个并列判断条件。
2. 不使用+运算符的等价实现方案
可以实现完全相同的逻辑,以下是两种常用的等价写法:
方案1:使用按位或运算替代加法
由于每个返回值的二进制位互不重叠,按位或运算的结果和加法完全一致,Oracle 12c及以上版本可使用内置BITOR函数实现:
BITOR( BITOR( case when t1.id is not null then 1 else 0 end, case when t2.id is not null then 2 else 0 end ), case when t3.id is not null then 4 else 0 end ) filter,
方案2:使用单层CASE枚举所有状态组合
直接通过条件判断返回最终编码值,完全不涉及算术运算,兼容所有Oracle版本:
case when t1.id is not null and t2.id is not null and t3.id is not null then 7 when t1.id is not null and t2.id is not null then 3 when t1.id is not null and t3.id is not null then 5 when t2.id is not null and t3.id is not null then 6 when t1.id is not null then 1 when t2.id is not null then 2 when t3.id is not null then 4 else 0 end filter,
方案3:结合NVL2简化判断逻辑(可选优化)
如果允许使用NVL2函数简化非空判断,还可以进一步缩短代码,搭配BITOR使用完全不需要加法运算符:
BITOR(BITOR(NVL2(t1.id,1,0), NVL2(t2.id,2,0)), NVL2(t3.id,4,0)) filter,
内容的提问来源于stack exchange,提问作者samsamara
相关产品推荐
相关产品推荐

