coalesce函数查询条件改写思路

1、问题

最近遇到一个Coalesce函数对null值处理后作为赋值条件的性能问题,例子如下:

bash 复制代码
select count(1) from (
select t1.id,t1.c1,t2.c2,coalesce(t1.c1,t2.c1) as state
from t1,t2 where t1.id=t2.id 
) where state='A1'

计划:

这里会做成布尔表达式,而函数中列条件过滤性较好,此时可以思考转换改写成or条件,coalesce(t1.c1,t2.c1)意思是t1.c1 is null时,就取t2.c1值,最终求t1.c1='A1',只需要处理t1.c1为null值的情况,所以应该考虑t1.c1是null值时t2.c1为'A1'的情况。

2、改写

bash 复制代码
select count(1) from (select t1.*  
from t1,t2 where t1.id=t2.id  and t1.c1='A1' 
union all
select t1.*
from t1,t2 where
t1.id=t2.id 
and (t1.c1 is null and t2.c1='A1'));

计划:

最终改写成union all,分别求t1.c1='A1'和t1.c1 is null的处理情况,关联列是主键关联,因此不存在重复值,可以改成成union all。最终从0.2s下降到0.008s

3、小结

coalesce函数中的列条件过滤性较好,可以思考改写成or条件,然后or条件可以转换成union all,避免optimizer_or_nbexp参数规则影响。