小编cha*_*shi的帖子

在大表中搜索一些结果而不扫描整个表

我需要搜索一个非常大的PostgreSQL表(500+M行),我想限制返回的搜索结果,但是使用“limit”关键字并不能阻止对整组数据的搜索(正确吗?)

想象一下我的搜索结果包含 1M 行,但我只需要搜索结果中的前 100 条记录!PostgreSQL 数据库是否必须在内存中临时创建这 1M 搜索结果行,然后给我所需的 100 个结果?

或者有什么办法告诉PostgreSQL一旦找到100条记录就停止搜索?

这是我的表,当然还没有填充 500M 记录!

CREATE TABLE con
(
  id bigserial NOT NULL,
  tag1 integer NOT NULL DEFAULT 0,
  tag2 integer NOT NULL DEFAULT 0,
  ref1 integer NOT NULL DEFAULT 0,
  ref2 integer NOT NULL DEFAULT 0,
  CONSTRAINT con_pkey PRIMARY KEY (id)
)
Run Code Online (Sandbox Code Playgroud)

以及测试查询的解释分析:

explain analyze SELECT * FROM con where tag1 = '64813' and tag2 = '80'
Run Code Online (Sandbox Code Playgroud)
Seq Scan on con  (cost=0.00..3215204.72 rows=2470 width=112) (actual time=0.016..36970.528 rows=7505 loops=1)
   Filter: …
Run Code Online (Sandbox Code Playgroud)

postgresql performance performance-tuning

2
推荐指数
1
解决办法
2787
查看次数