oracle Like模糊查詢與帶有關鍵字Reverse的索引應用

oracle Like模糊查詢與帶有關鍵字Reverse的索引應用

在對oracle的SQL優化過程當中常常會遇到【like'%abc'】破壞索引的問題,可是若是真有此類需求,該如何在不破壞索引的基礎上進行查詢呢。

上代碼

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 Optimizer=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 Optimizer=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 Optimizer=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 Optimizer=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)oracle

重慶思莊18年5月OCP認證培訓週末班正在授課,歡迎聯繫試聽!新的OCP週末班將於6月2日開課,火熱報名中,名額有限,請提早預約!更多詳情訪問思莊網站諮詢在線客服。函數

相關文章
相關標籤/搜索