日期:2014-05-16  浏览次数:20441 次

oracle语句优化规则八
转载来源:IT专家网 作者:Peak Wong
1. 用UNION替换OR (适用于索引列)
  通常情况下, 用UNION替换WHERE子句中的OR将会起到较好的效果。 对索引列使用OR将造成全表扫描。注意, 以上规则只针对多个索引列有效。 如果有column没有被索引, 查询效率可能会因为你没有选择OR而降低。

  在下面的例子中, LOC_ID 和REGION上都建有索引。

  高效:

  SELECT LOC_ID , LOC_DESC , REGION
  FROM LOCATION
  WHERE LOC_ID = 10
  UNION
  SELECT LOC_ID , LOC_DESC , REGION
  FROM LOCATION
  WHERE REGION = “MELBOURNE”


  低效:

  SELECT LOC_ID , LOC_DESC , REGION
  FROM LOCATION
  WHERE LOC_ID = 10 OR REGION = “MELBOURNE”


  如果你坚持要用OR, 那就需要返回记录最少的索引列写在最前面。

  注意:

  WHERE KEY1 = 10 (返回最少记录)

  OR KEY2 = 20 (返回最多记录)

  ORACLE 内部将以上转换为

  WHERE KEY1 = 10 AND((NOT KEY1 = 10) AND KEY2 = 20)

  :

  下面的测试数据仅供参考: (a = 1003 返回一条记录 , b = 1 返回1003条记录)
  
  SQL> select * from unionvsor /*1st test*/
 2   where a = 1003 or b = 1;
 1003 rows selected.
 Execution Plan
 ----------------------
    0      SELECT STATEMENT Optimizer=CHOOSE
 1    0   CONCATENATION
 2    1     TABLE ACCESS (BY INDEX ROWID) OF 'UNIONVSOR'
 3    2       INDEX (RANGE SCAN) OF 'UB' (NON-UNIQUE)
    4    1     TABLE ACCESS (BY INDEX ROWID) OF 'UNIONVSOR'
 5    4       INDEX (RANGE SCAN) OF 'UA' (NON-UNIQUE)
    Statistics
 ----------------------
    0 recursive calls
 0 db block gets
 144 consistent gets
 0 physical reads
 0 redo size
 63749 bytes sent via SQL*Net to client
 7751 bytes received via SQL*Net from client
 68 SQL*Net roundtrips to/from client
 0 sorts (memory)
    0 sorts (disk)
    1003 rows processed
 SQL> select * from unionvsor /*2nd test*/
 2 where b = 1 or a = 1003 ;
 1003 rows selected.
 Execution Plan
 ----------------------
    0      SELECT STATEMENT Optimizer=CHOOSE
 1    0   CONCATENATION
 2    1     TABLE ACCESS (BY INDEX ROWID) OF 'UNIONVSOR'
 3    2       INDEX (RANGE SCAN) OF 'UA' (NON-UNIQUE)
    4    1     TABLE ACCESS (BY INDEX ROWID) OF 'UNIONVSOR'
 5    4       INDEX (RANGE SCAN) OF 'UB' (NON-UNIQUE)
    Statistics
 ----------------------
    0 recursive calls
 0 db block gets
 143 consistent gets
 0 physical reads
 0 redo size
 63749 bytes sent via SQL*Net to client
 7751 bytes received via SQL*Net from client
 68 SQL*Net roundtrips to/from client 0 sorts (memory)
    0 sorts (disk)
    1003 rows processed
    SQL> select * from unionvsor /*3rd test*/
 2 where a = 1003
 3 union
 4   select * from unionvsor
 5   where b = 1;
 1003 rows selected. Execution Plan
 ----------------------
    0      SELECT STATEMENT Optimizer=CHOOSE
 1    0   SORT (UNIQUE)
    2    1     UNION-ALL
 3    2       TABLE ACCESS (BY INDEX ROWID) OF 'UNIONVSOR'
 4    3         INDEX (RANGE SCAN) OF 'UA' (NON-UNIQUE)