数据库
首页 > 数据库> > SQL优化: 匹配中间字段内容的一种写法

SQL优化: 匹配中间字段内容的一种写法

作者:互联网

众所周知,当索引字段使用like时,只有前缀查找才会走索引,但难免有时候需要匹配字符串中间部分内容,如果这个时候,选择字段只有索引字段,会走索引,例如:

例: select tob.object_name from test_objects tob
where tob.object_name like '%EFGHI%';

注: object_name 有索引

SELECT STATEMENT, GOAL = ALL_ROWS			105	2745	107055
 INDEX FAST FULL SCAN	LOTPYTHON	IND_TEST_OBJECTS001	105	2745	107055

但如果选择内容包含非索引字段时,是不会走索引的。

例:select tob.object_name,tob.object_id from test_objects tob
where tob.object_name like '%EFGHI%'

注: object_name 有索引

SELECT STATEMENT, GOAL = ALL_ROWS			307	2745	120780
 TABLE ACCESS FULL	LOTPYTHON	TEST_OBJECTS	307	2745	120780

那有没有好的办法呢,其实还是可以通过某种写法规避的。

例如:with test_like as (select object_name from test_objects 
where object_name like '%EFGHI%'
union all
select '不可能出现的词' as  object_name from dual     
)
select tob.object_name,tob.object_id from test_objects tob
where tob.object_name in (select * from test_like);

SELECT STATEMENT, GOAL = ALL_ROWS			112	1	110
 HASH JOIN			112	1	110
  NESTED LOOPS			112	1	110
   NESTED LOOPS			112	1	110
    STATISTICS COLLECTOR					
     VIEW	SYS	VW_NSO_1	108	2746	181236
      HASH UNIQUE				1	181236
       VIEW	LOTPYTHON		108	2746	181236
        UNION-ALL					
         INDEX FAST FULL SCAN	LOTPYTHON	IND_TEST_OBJECTS001	105	2745	107055
         FAST DUAL			2	1	
    INDEX RANGE SCAN	LOTPYTHON	IND_TEST_OBJECTS001	2	1	
   TABLE ACCESS BY INDEX ROWID	LOTPYTHON	TEST_OBJECTS	3	1	44
  TABLE ACCESS FULL	LOTPYTHON	TEST_OBJECTS	3	1	44

该写法有一个限制条件,就是查询返回的数据量不是很大,当然,数据量返回很大的时候,也不应该走索引。

标签:匹配,name,object,索引,test,SQL,tob,LOTPYTHON,写法
来源: https://blog.csdn.net/zhougongping/article/details/123091177