日期:2014-05-17  浏览次数:20952 次

oracle含聚合函数的sql优化问题
现有三张表,使用了分区建表, 都有 id,和mileage字段,需要联合查询得到各个id某一时间段对应的mileage总和, 
我写的sql如下:

select TARGET_ID, sum(mileage)as mileage from (
(select/*+ index(messageIDindex,messageTimeIndex)*/ TARGET_ID, sum(mileage) as mileage from cwits.th_messageInfo where built_time>1269187200 and built_time<1269273600 and mileage>0 group by TARGET_ID )union all(select/*+ index(messageIDindex,messageTimeIndex)*/ TARGET_ID, sum(mileage) as mileage from cwits.th_positionInfo where built_time>1269187200 and built_time<1269273600 and mileage>0 group by TARGET_ID )union all(select/*+ index(messageIDindex,messageTimeIndex)*/ TARGET_ID, sum(mileage) as mileage from cwits.th_reportInfo where built_time>1269187200 and built_time<1269273600 and mileage>0 group by TARGET_ID )) group by TARGET_ID;
三张表每天的数据量都在1000万以上, 开始没建索引查询下来要80m左右,后来针对每个表的 target_id和 built_time建了local分区索引,但是查询下来也要80m左右甚至更长。。
那位大侠帮忙看看有什么办法提高下效率呢?

------解决方案--------------------
首先,3表并无相互关联,所以,你在target_id和 built_time上建索引没什么用。

在built_time上建立索引试试看。


另外,你的hint写法明显错误,正确应为:

select/*+ index(table_name index_name)*/ 


走时间索引,不要走target_id和 built_time索引。
------解决方案--------------------
另外,比较下走索引与不走索引的差别,其实,如果数据访问比例大,ORACLE CBO宁愿选择全表扫描。


此时,你应该抛弃使用索引。