向我解释一个 postgresql EXPLAIN

发布于 2024-10-07 05:49:56 字数 834 浏览 6 评论 0原文

在这里得到这个查询:

EXPLAIN
SELECT persons.id AS id, ppm.first
FROM myschema.persons
INNER JOIN myotherschema.ppm ON persons.key = ppm.pid
WHERE persons.id = 279759;

ppm.pid是主键并且在索引中:

CREATE INDEX ppm_pkey_index
  ON myotherschema.ppm
  USING btree
  (pid);

所以这里是解释:

Hash Join  (cost=8.31..3105.40 rows=306 width=23)
  Hash Cond: (textin(int4out(ppm.pid)) = persons.key)
  ->  Seq Scan on ppm  (cost=0.00..2711.33 rows=61233 width=23)
  ->  Hash  (cost=8.29..8.29 rows=1 width=12)
        ->  Index Scan using pskey on persons  (cost=0.00..8.29 rows=1 width=12)
              Index Cond: (id = 279759)

它似乎没有使用ppm_pkey_index all:它似乎仍在扫描 61,233 行。这是为什么呢?难道是我读错了?推论:postgresql 中主键不是自动索引的吗?那么我的索引是多余的吗?

Got this here query:

EXPLAIN
SELECT persons.id AS id, ppm.first
FROM myschema.persons
INNER JOIN myotherschema.ppm ON persons.key = ppm.pid
WHERE persons.id = 279759;

The column ppm.pid is a primary key AND in the index:

CREATE INDEX ppm_pkey_index
  ON myotherschema.ppm
  USING btree
  (pid);

And so here's the EXPLAIN:

Hash Join  (cost=8.31..3105.40 rows=306 width=23)
  Hash Cond: (textin(int4out(ppm.pid)) = persons.key)
  ->  Seq Scan on ppm  (cost=0.00..2711.33 rows=61233 width=23)
  ->  Hash  (cost=8.29..8.29 rows=1 width=12)
        ->  Index Scan using pskey on persons  (cost=0.00..8.29 rows=1 width=12)
              Index Cond: (id = 279759)

It doesn't seem to be using the ppm_pkey_index at all: it still seems to be scanning 61,233 rows. Why is this? Am I misreading it? Corollary: aren't primary keys automatically indexed in postgresql? Is my index then redundant?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等风也等你 2024-10-14 05:49:56

主键在您的键上创建唯一索引。所以你的索引确实是多余的。

创建索引后,您是否在表上运行了真空分析?

sql> vacuum analyze myotherschema.ppm;

我现在看到另一个问题:ppm.pidpersons.key 是否具有相同的字段类型?由于不必要的数据转换,您可能会遇到性能问题,并且无法使用索引,因为您没有对连接时需要使用的转换函数建立索引...

Primary keys create UNIQUE INDEXES on your key. So your index is redundant indeed.

Did you run vacuum analyze on your table after creating the index?

sql> vacuum analyze myotherschema.ppm;

I see another problem now: are ppm.pid and persons.key of the same field type? You may run into perfomance issues due to unnecessary data conversions, and inability to use indexes because you are not indexing on casting functions you need to use on join...

作死小能手 2024-10-14 05:49:56

如果将其更改为以下内容会发生什么:

EXPLAIN
SELECT persons.id AS id, ppm.first
FROM myschema.persons
INNER JOIN myotherschema.ppm ON persons.id = 279759
AND persons.key = ppm.pid;

What happens if you change it to:

EXPLAIN
SELECT persons.id AS id, ppm.first
FROM myschema.persons
INNER JOIN myotherschema.ppm ON persons.id = 279759
AND persons.key = ppm.pid;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文