gpt4 book ai didi

sql - 为什么创建不相关的索引会使我的查询更快?

转载 作者:行者123 更新时间:2023-11-29 11:44:47 25 4
gpt4 key购买 nike

我有一张 table :

debts (
name text,
inv_no integer,
inv_type text,
status text,
);

我有以下选择:

SELECT COUNT(*) FROM debts WHERE name = '...' AND inv_no = 100 AND inv_type = '...';

为了优化其他东西,我添加了:

CREATE INDEX ON debt (status);

我在 SELECT 的任何地方都没有提到状态,但正在运行......

EXPLAIN SELECT COUNT(*)... (as above)

...在创建索引之前和之后,成本从 16.65..16.66 变为 1.25..1.26。为什么?

完整的解释(分析,详细)之前/之后:

之前:

QUERY PLAN
----------
Aggregate (cost=16.65..16.66 rows=1 width=0) (actual time=0.126..0.128 rows=1 loops=1)
Output: count(*)
-> Seq Scan on ab123456.debts (cost=0.00..16.65 rows=1 width=0) (actual time=0.106..0.106 rows=0 loops=1)
Output: name, inv_no, inv_type, status
Filter: ((debts.name = '...'::text) AND (debts.inv_type = '...'::text) AND (debts.inv_no = 100))
Total runtime: 0.387 ms

之后:

QUERY PLAN
----------
Aggregate (cost=1.25..1.26 rows=1 width=0) (actual time=0.031..0.033 rows=1 loops=1)
Output: count(*)
-> Seq Scan on ab123456.debts (cost=0.00..1.25 rows=1 width=0) (actual time=0.024..0.024 rows=0 loops=1)
Output: name, inv_no, inv_type, status
Filter: ((debts.name = '...'::text) AND (debts.inv_type = '...'::text) AND (debts.inv_no = 100))
Total runtime: 0.118 ms

最佳答案

一些实用程序语句(包括 CREATE INDEX!)在执行时更新表统计信息。 The manual:

For efficiency reasons, reltuples and relpages are not updated on-the-fly, and so they usually contain somewhat out-of-date values. They are updated by VACUUM, ANALYZE, and a few DDL commands such as CREATE INDEX.

大胆强调我的。因此,即使您的索引看起来完全不相关,更新的表统计信息也会产生影响 - 特别是对 count() 而言,它主要取决于所提到的两个统计信息。

相关:

关于sql - 为什么创建不相关的索引会使我的查询更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41896635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com