oracle 的rownum问题
rownum和top是不一样的,rownum用来分页是先全选出来,然后取多少条,效率是比较低的。
举例:
在工作中碰见这样的问题
select wfcount,cid from (select count(customer_id) wfcount, customer_id cid
from aaa_review
where wonderful_flag = 1
group by customer_id
order by wfcount desc) where rownum <100
运行时间超过27秒
而把外层rownum取消:
select count(customer_id) wfcount, customer_id cid
from aaa_review
where wonderful_flag = 1
group by customer_id
order by wfcount desc
竟然在0.8秒就可以完成,差距非常之大
后来,分析oracle的调用计划,发现竟然用了不同的索引,而且,慢的那个用了一个狠不相关的全局索引,可见,加上rownum外层查询之后,oracle处理起来和不加rownum的外层处理是完全不一样的。
后来改动为:
select wfcount,cid from (select /*+ index(aaa_review wonderful_IwDX) */ count(customer_id) wfcount, customer_id cid
from aaa_review
where wonderful_flag = 1
group by customer_id
order by wfcount desc) where rownum <100
虽然运行时间是0.9秒左右,比不加rownum慢一些,但是已经可以接受