Sql 为什么我的查询使用LIKE执行seq扫描?
我有一张220万行的桌子Sql 为什么我的查询使用LIKE执行seq扫描?,sql,postgresql,indexing,Sql,Postgresql,Indexing,我有一张220万行的桌子 Table "public.index" Column | Type | Modifiers -----------+-----------------------------+-----------------------------------------
Table "public.index"
Column | Type | Modifiers
-----------+-----------------------------+-----------------------------------------------------
fid | integer | not null default nextval('index_fid_seq'::regclass)
location | character varying |
Indexes:
"index_pkey" PRIMARY KEY, btree (fid)
"location_index" btree (location text_pattern_ops)
位置是文件的完整路径,但我需要使用文件所在文件夹的名称进行查询。该文件夹名称在表中是唯一的
为了避免开始时出现%
,我搜索我知道的完整路径:
select fid from index where location like '/path/to/folder/%'
解释和分析:
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Seq Scan on index (cost=0.00..120223.34 rows=217 width=4) (actual time=1181.701..1181.701 rows=0 loops=1)
Filter: ((location)::text ~~ '/path/to/folder/%'::text)
Rows Removed by Filter: 2166034
Planning time: 0.954 ms
Execution time: 1181.748 ms
(5 rows)
问题不在于如何解决问题,因为 我发现在我的案例中: 创建
foldername\u索引时
create index on index (substring(location, '(?<=/path/to/)[^\/]*');
我还遵循了这里关于堆栈溢出的说明,这就是为什么我使用text\u pattern\u ops
,它没有改变任何东西。不幸的是,我无法安装新模块
所以:为什么我的查询要执行序列扫描?经过反复思考,我自己找到了解决方案。虽然对某些人来说这可能是显而易见的,但它可能会帮助其他人:
/path/to/folder
实际上是/path/to/folder/
(路径中有下划线)。但是\uuu
在SQL中是一个通配符(比如%
)
使用seq scan是因为索引无法筛选任何行,因为下划线之前的部分对于所有行都是相同的
select fid from index where location like '/the\_path/to/folder/%'
使用索引扫描。通过反复思考,我自己找到了解决方案。虽然对某些人来说这可能是显而易见的,但它可能会帮助其他人:
/path/to/folder
实际上是/path/to/folder/
(路径中有下划线)。但是\uuu
在SQL中是一个通配符(比如%
)
使用seq scan是因为索引无法筛选任何行,因为下划线之前的部分对于所有行都是相同的
select fid from index where location like '/the\_path/to/folder/%'
使用索引扫描。我问了一个类似的问题@dba,他们告诉我这是StackOverflow的问题,因为这不是关于管理,而是使用数据库。谢谢@RoVo。确保每周至少分析一次您的表。我在dba问了一个类似的问题,他们告诉我这是StackOverflow的问题,因为这不是关于管理,而是使用数据库。谢谢@RoVo。确保每周至少分析一次您的表。
select fid from index where location like '/the_path/to/folder/%'
select fid from index where location like '/the\_path/to/folder/%'