宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

很多时候,我们要进行字符串匹配,在SQL语句中,我们通常使用like来达到我们搜索的目标。但经过实际测试发现,like的效率与instr函数差别相当大。下面是一些测试结果: 

select instr’abcd’,’a’) from dual;  –返回1
select instr’abcd’,’c’) from dual;  –返回3
select instr’abcd’,’e’) from dual;    –返回0

该函数可以用于模糊查询以及判断包含关系:

例如:

① select code, name, dept, occupation  from staff  where instrcode, ‘001’) > 0;

  等同于

  select code, name, dept, occupation  from staff  where code like ‘%001%’ ;

② select ccn,mas_loc from mas_loc where instr’FH,FHH,FHM’,ccn)>0;

  等同于

  select ccn,mas_loc from mas_loc where ccn in ‘FH’,’FHH’,’FHM’);

SQL> select count*) from t where instrtitle,‟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

注: 
instrtitle,’oracle‟)>0 相当于like 

instrtitle,’oracle‟)=0 相当于not like 

–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

–4.从倒数第1个字符开始,搜索第2次出现子串的位置

SQL> select instr’oracleor’,’or’, -1, 2) position from dual;

POSITION

———-    

     1

经典例子:

select * from tuser a where instr’,’||select substrowner,8,lengthowner)) from os_currentstep where entry_id=4252300)||’,’,’,’||a.id||’,’)>0;

select substrowner,8,lengthowner)) from os_currentstep where entry_id=4252300) 结果为字符串:3993,451,1889,1482

如果直接这么写:select * from tuser a where a.id in select substrowner,8,lengthowner)) from os_currentstep where entry_id=4252300)会报无效数字