Oracle中的like優化

edwardking888發表於2010-05-13

。儘量不要使用 like '%..%'
2。對於 like '..%..' (不以 % 開頭),Oracle可以應用 colunm上的index

3。對於 like '%...' 的 (不以 % 結尾),可以利用reverse + function index 的形式,變化成 like '..%'


程式碼:


-- '建測試表和Index,注意,重點在於帶reverse的function index。同時,一定要使用CBO才行……

sys@mescp> select reverse('123') from dual;REVERSE('123')

--------------------------------

321

1 row selected.

sys@mescp> create table test_like as select object_id,object_name from dba_objects;

Table created.

sys@mescp> create index test_like__name on test_like(object_name);

Index created.

sys@mescp> create index test_like__name_reverse on test_like(reverse(object_name));

Index created.
sys@mescp> analyze table test_like compute statistics for table for all indexes;

Table analyzed.

sys@mescp> set autotrace trace exp


-- '常量開頭的like , 會利用index ,沒問題…… '

sys@mescp> select * from test_like where object_name like 'AS%';


Execution Plan

----------------------------------------------------------

0 SELECT STATEMENT ptimizer=CHOOSE (Cost=2 Card=655 Bytes=15720)

1 0 TABLE ACCESS (BY INDEX ROWID) OF 'TEST_LIKE' (Cost=2 Card=655Bytes=15720)

2 1 INDEX (RANGE SCAN) OF 'TEST_LIKE__NAME' (NON-UNIQUE) (Cost=2 Card=118)


--'開頭和結尾都是 % ,對不起,很難優化'

sys@mescp> select * from test_like where object_name like '%%';


Execution Plan

----------------------------------------------------------

0 SELECT STATEMENT ptimizer=CHOOSE (Cost=6 Card=655 Bytes=15720)

1 0 TABLE ACCESS (FULL) OF 'TEST_LIKE' (Cost=6 Card=655 ytes=15720)


-- '以常量結束,直接寫的時候是不能應用index的'

sys@mescp> select * from test_like where object_name like '%S';

Execution Plan

----------------------------------------------------------

0 SELECT STATEMENT ptimizer=CHOOSE (Cost=6 Card=655 Bytes=15720)

1 0 TABLE ACCESS (FULL) OF 'TEST_LIKE' (Cost=6 Card=655 Bytes=15720)


--'以常量結束的,加個reverse 函式,又可以用上index了'

sys@mescp> select * from test_like where reverse(object_name)like reverse('%AS');

Execution Plan

----------------------------------------------------------

0 SELECT STATEMENT ptimizer=CHOOSE (Cost=2 Card=655 Bytes=15720)

1 0 TABLE ACCESS (BY INDEX ROWID) OF 'TEST_LIKE' (Cost=2 Card=655 Bytes=15720)

2 1 INDEX (RANGE SCAN) OF 'TEST_LIKE__NAME_REVERSE' (NON-UNIQUE) (Cost=2 Card=118)

 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/8183550/viewspace-662618/,如需轉載,請註明出處,否則將追究法律責任。

相關文章