问题的原因比较清楚:
我其实是2个表关联查询:订单产品表(A)-->订单表(B)
其中A表中有350多万记录 B表中有15万记录
我的sql大概是这样
select * from (
select * from A a, B b
where
a.orderId=b.id
and b.f1 =1000 --- 查询条件
and b.f2=2000 ---查询条件
order by a.created_dt
) where rownum<100
注意红色的内容:
红色的内容是两个条件,已经给这两个建了一个索引,两个字段的联合索引
这个sql 执行是 150秒左右
如果去掉红色部分,那么就是
select * from (
select * from A a, B b
where
a.orderId=b.id
order by a.created_dt
) where rownum<100
这个语句是1.7秒左右
如果去掉order by
select * from (
select * from A a, B b
where
a.orderId=b.id
and b.f1 =1000 --- 查询条件
and b.f2=2000 ---查询条件
) where rownum<100
那么速度是1.1秒左右
可是条件和orderby都是必须的,order by 上面也有索引,可是在上面3种查询中explain 都不曾用到。
---------------------------------
问题如上:
感谢阮容,帮助分析并最终解决此问题。
select * from (
select * from A a, B b
where
a.orderId=b.id
and b.f1 =1000 --- 查询条件
and b.f2=2000 ---查询条件
order by a.created_dt
) where rownum<100
之前已经说过A表是大表,200多万记录,B表是小表 15万记录,执行计划显示A表的的全表扫描没有使用索引,经查看两表关联a.orderId=b.id的地方orderId竟无索引,因此新建了一个索引在A表的orderid上。
原先150秒的sql现在一下子变成1秒了
感谢大家。
本贴来源: