1. 程式人生 > >richard的專欄([email protecte

richard的專欄([email protecte

ORACLELikeInstr模糊查詢效能大比拼

instr(title,'手冊')>0  相當於  title like '%手冊%'

instr(title,'手冊')=1  相當於  title like '手冊%'

instr(title,'手冊')=0  相當於  title not like '%手冊%'

t表中將近有1100萬資料,很多時候,我們要進行字串匹配,在SQL語句中,我們通常使用like來達到我們搜尋的目標。但經過實際測試發現,like的效率與instr函式差別相當大。下面是一些測試結果:

SQL> set timing on
SQL> select count(*) from t where instr(title,'手冊

')>0;

  COUNT(*)
----------
     65881

Elapsed: 00:00:11.04
SQL> select count(*) from t where title like '%手冊%';

  COUNT(*)
----------
     65881

Elapsed: 00:00:31.47
SQL> select count(*) from t where instr(title,'手冊')=0;

  COUNT(*)
----------
  11554580

Elapsed: 00:00:11.31
SQL> select count(*) from t where title not like '%手冊

%';

  COUNT(*)
----------
  11554580

另外,我在結另外一個2億多的表,使用8個並行,使用like查詢很久都不出來結果,但使用instr,4分鐘即完成查詢,效能是相當的好。這些小技巧用好,工作效率提高不少。通過上面的測試說明,ORACLE內建的一些函式,是經過相當程度的優化的。

instr(title,’aaa’)>0 相當於like

instr(title,’aaa’)=0 相當於not like

特殊用法:

select   id, name from users where instr('101914, 104703', id) > 0; 
  

它等價於 
select   id, name from users where id = 101914 or id = 104703;

一般來說,在Oracle資料庫中,我們對tb表的name欄位進行模糊查詢會採用下面兩種方式:
1.select * from tb where name like '%XX%';
2.select * from tb where instr(name,'XX')>0;

若是在name欄位上沒有加索引,兩者效率差不多,基本沒有區別。為提高效率,我們在name欄位上可以加上非唯一性索引:
create index idx_tb_name on tb(name);

這樣,再使用

select * from tb where instr(name,'XX')>0;

這樣的語句查詢,效率可以提高不少,表資料量越大時兩者差別越大。但也要顧及到name欄位加上索引後DML語句會使索引資料重新排序的影響。