oracle instr函式(oracle 用instr 來代替 like)
對於instr函式,我們經常這樣使用:從一個字串中查詢指定子串的位置。例如:
SQL> select instr('oracle','or') position from dual;
POSITION
----------
1
從字串'oracle'的第一個位置開始,向後查詢第一個出現子串'or'出現的位置。
其實instr共有4個引數,格式為“instr(string, substring, startposition, occurrence)”。可實現子串的如下搜尋:
1.從指定位置開始搜尋子串
2.指定搜尋第幾次出現的子串的位置
3.從後向前搜尋
--1.從第3個字元開始搜尋
SQL> select instr('oracleor','or', 3) position from dual;
POSITION
----------
7
--2.從第1個字元開始,搜尋第2次出現子串的位置
SQL> select instr('oracleor','or', 1, 2) position from dual;
POSITION
----------
7
--3.從倒數第1個字元開始,搜尋第1次出現子串的位置
SQL> select instr('oracleor','or', -1, 1) position from dual;
POSITION
----------
7
--3.從倒數第1個字元開始,搜尋第2次出現子串的位置
SQL> select instr('oracleor','or', -1, 2) position from dual;
POSITION
----------
1
oracle用instr代替like
表中將近有100萬資料,很多時候,我們要進行字串匹配,在SQL語句中,我們通常使用like來達到我們搜尋的目標。但經過實際測試發現,like的效率與instr函式差別相當大。下面是一些測試結果:
SQL> set timing on
SQL> select count(*) from t where instr(title,’oracle’)>0;
COUNT(*)
———-
5478
Elapsed: 00:00:11.04
SQL> select count(*) from t where title like ‘%oracle%’;
COUNT(*)
———-
5478
Elapsed: 00:00:31.47
SQL> select count(*) from t where instr(title,’oracle’)=0;
COUNT(*)
———-
994530
Elapsed: 00:00:11.31
SQL> select count(*) from t where title not like ‘%oracle%’;
COUNT(*)
———-
994530
注:
instr(title,'oracle’)>0 相當於like
instr(title,'oracle’)=0 相當於not like