下面一段SQL,如果不加where str1 = '1' 执行速度很快,仅需5秒,但是加入where查询之后,无法产生结果,总体数据量仅有20万,各位大拿给看看是什么原因。
SQL如下:
select
count(distinct str1)
from
(
select
a1.str0
,a1.str4
,case when a2.str3=1 then '1' else '0' end as str1
from table1 a1
left join table2 a2
on a1.str0=a2.str0
)
where str1 = '1'
初步分析如下:
1)加上"where str1 = '1'"慢的原因: 由于这个str1只有2个值(0或者1),一般不会采用索引,即使采用索引,也和tablescan一样慢。所以,加上这个where条件的话,相当于增加了一层tablescan循环,会很慢。
2)这个SQL语句问题很多,建议考虑好好修改这个SQL:经过"case when a2.str3=1 then '1' else '0' end as str1"之后,str1只有2个值(0或者1),没有必要再"distinct str1",没有这个distinct也可以计算出需要的值。
3)该SQL的access plan中可能包括包含多层循环和tablescan(Next Loop Join),可以自己抽取一下access plan,自己分析一下,或者贴出来,大家分析一下。例如使用db2explain...
对str1进行where再做count(distinct)肯定是1啊,如果这样做慢可能是distinct的时候有问题,你试一下把didtinct换成group by。
一般sql不正常执行慢:
先对两个表做reorg,runstatus,如果没用,再用db2expln -d bidbdw -q "select * from test" -g -t看一下执行计划。