標籤:style blog http os 2014 re
from http://www.itpub.net/thread-1852897-1-1.html
有論壇朋友在上面的文章裡問SQL為什麼不走索引,正好這兩天我也剛剛在看SQL最佳化,於是試著回答了一下.
下面是原來的SQL:
select o.order_id as orderId from order_info o, member m
where m.member_id = o.member_id
and o.is_delete = ‘N‘
/*and (to_date(nvl(o.paid_time,o.commit_time), ‘YYYY-MM-DD hh24:mi:ss‘) >=
to_date(‘2014-03-27 00:00:00‘, ‘YYYY-MM-DD hh24:mi:ss‘))
and (to_date(nvl(o.paid_time,o.commit_time), ‘YYYY-MM-DD hh24:mi:ss‘) <=
to_date(‘2014-03-27 23:59:59‘, ‘YYYY-MM-DD hh24:mi:ss‘))*/
and o.commit_time like ‘2014-03-27%‘
and ((o.payment_mode = ‘KDFH‘ and o.IS_PAID = ‘Y‘) or
(o.payment_mode = ‘HDFK‘))
and o.order_state NOT in (18, 19, 25)
and (exists (select 1
from fecerp.sys_role_select rs, fecerp.sys_role_user su
where su.role_id = rs.role_id
and su.user_id = 3132
and su.is_delete = ‘N‘
and rs.othera = 0) OR exists
(select 1
from fecerp.sys_role_select rs,
fecerp.sys_role_user su,
product_yw_catalog pyc,
product_yw_catalog_goods ycg,
order_item oi
where su.role_id = rs.role_id
and pyc.yw_catalog_id = ycg.wy_catalog_id
and su.user_id = 3132
and rs.othera <> 0
and su.is_delete = ‘N‘
and ‘,‘ || rs.bus_ids || ‘,‘ like
‘%,‘ || pyc.yw_catalog_id || ‘,%‘
and oi.order_id = o.order_id
and oi.is_delete = ‘N‘
and ycg.goods_no = oi.goods_no))
and (select m.multi_channel_id
from ec_multi_channel m
where m.multi_channel_id = o.multi_channel_id) in
(select ser.multi_channel_id
from fecerp.sys_role_channel ser, fecerp.sys_role_user uss
where ser.role_id = uss.role_id
and ser.is_delete = ‘N‘
and uss.is_delete = ‘N‘
and uss.user_id = 3132)
執行計畫:
order_info 索引如下:
和統計資訊的關係不大,至少表order_info 的統計資訊是正確的,否則table full access的cost不會這麼高.
不走索引應該是下面的原因.
- o.is_delete = ‘N‘ --這個欄位上沒有索引
- o.commit_time like ‘2014-03-27%‘ --這個欄位上沒有索引
- ((o.payment_mode = ‘KDFH‘ and o.IS_PAID = ‘Y‘) or (o.payment_mode = ‘HDFK‘)) --在payment_mode 和 IS_PAID 上雖然分別有索引,但是 對於條件 o.payment_mode = ‘KDFH‘ and o.IS_PAID = ‘Y‘) 如果走索引,那麼是需要同時判斷這兩個欄位的值. 這裡沒有基於這兩個欄位的索引,所以也走不了.
- o.order_state NOT in (18, 19, 25) -- not in 排除常量,走不了索引
推薦在 payment_mode 和 IS_PAID 上建立一個複合式索引.