大多数情况下,oracle数据库内置的查询优化策略还是很成功的,但偶尔也有犯2的时候,即使有索引,也会做全表扫描,可以参考以下语句的写法,强制让select语句使用索引
1 CREATE OR REPLACE VIEW V_RES_CBA AS 2 SELECT /*+INDEX(SEG IDX_T_RES_ALLOSEG_ALLOID)*/ 3 ALLO.ALLOID AS RESID, 4 NULL AS AWB, 5 ALLO.ALLOTMENT AS ALLO_ID, 6 DAYS.FDATE + NVL(SEG.DAYSDISP, 0) AS FDATE, 7 ALLO.SPECULD AS SPECULD 8 FROM T_RES_ALLO ALLO, T_RES_ALLOSEG SEG, V_FDATE DAYS 9 WHERE ALLO.ALLOID = SEG.ALLOID10 AND ((ALLO.ALLOIND = 'A' AND ALLO.ALLO_DATE = DAYS.FDATE) OR11 (ALLO.ALLOIND = 'S' AND12 NVL(ALLO.SDATE, ALLO.ALLO_DATE) = DAYS.FDATE)) 13 UNION14 SELECT /*+INDEX(SEG IDX_T_RES_ALLOSEG_ALLOID)*/15 ALLO.ALLOID AS RESID,16 NULL AS AWB, 17 ALLO.ALLOTMENT AS ALLO_ID, 18 DAYS.FDATE + NVL(SEG.DAYSDISP, 0) AS FDATE, 19 ALLO.SPECULD AS SPECULD 20 FROM T_RES_ALLO ALLO, T_RES_ALLOSEG SEG, V_FDATE DAYS21 WHERE ALLO.ALLOID = SEG.ALLOID22 AND ALLO.ALLO_DATE IS NULL23 AND ALLO.ALLOIND = 'A'24 AND (DAYS.FDATE >= ALLO.SDATE AND DAYS.FDATE <= ALLO.EDATE AND25 INSTR(ALLO.WEEKDAY, DAYS.WEEKDAY) > 0) 26 AND NOT EXISTS (SELECT subQuery.ALLOID27 from T_RES_ALLO subQuery28 where subQuery.ALLO_DATE = DAYS.FDATE29 and subQuery.ALLOTMENT = ALLO.ALLOTMENT)30 ;
要点:
1、/*+INDEX(SEG IDX_T_RES_ALLOSEG_ALLOID)*/ 这里的/*...*/中间不要有空格
2、表名要用别名,即:以上面的sql语句为例,要使用SEG,而不是T_RES_ALLOSEG