数据库教程:Oracle中Like与Instr模糊查询性能大比拼

instr(title,’手册’)>0 相当于 title like ‘%手册%’ instr(title,’手册’)=1 相当于 title like

  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的instr函数与索引配合提高模糊查询的效率   

一般来说,在oracle数据库中,我们对tb表的name字段进行模糊查询会采用下面两种方式: 

  select * from tb where name like '%xx%';   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语句会使索引数据重新排序的影响。

以上所述是小编给大家介绍的oracle中like与instr模糊查询性能大比拼,希望对大家有所帮助

需要了解更多数据库技术:Oracle中Like与Instr模糊查询性能大比拼,都可以关注数据库技术分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/dtteaching/804792.html

(0)
上一篇 2021年9月16日
下一篇 2021年9月16日

精彩推荐