首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何为等于和大于的多列创建索引?

如何为等于和大于的多列创建索引?
EN

Stack Overflow用户
提问于 2022-11-07 10:31:29
回答 2查看 40关注 0票数 0

我有一张桌子,它有这些栏:

代码语言:javascript
运行
复制
 id       | tx_hash | tx_status | created_at
----------+---------+-----------+---------------------------
15000000  | 0x0011  | 0         | 2021-07-30 06:42:00.267694
15000001  | 0x0011  | 0         | 2021-07-30 06:42:00.267694
15000002  | 0x0011  | 0         | 2021-07-30 06:42:00.267694
...
16000000  | 0x0011  | 0         | 2021-07-30 06:42:00.267694

我想按2列查询:tx_statusequal查询,id按“大于”查询。我的SQL查询是:

代码语言:javascript
运行
复制
select id, tx_hash, tx_status, created_at 
from pool_transaction_entries 
where tx_status = 0 and id > 15006000 
order by id desc 
limit 1;

我发现它很慢!

这是分析结果:

代码语言:javascript
运行
复制
postgres=> explain analyze verbose select id, tx_hash, tx_status, created_at from pool_transaction_entries where tx_status = 0 and id > 15006000 order by id  desc limit 1;
                                                                                        QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=0.43..133.80 rows=1 width=87) (actual time=21415.241..21415.242 rows=0 loops=1)
   Output: id, tx_hash, tx_status, created_at
   ->  Index Scan Backward using pool_transaction_entries_pkey on public.pool_transaction_entries  (cost=0.43..3868.12 rows=29 width=87) (actual time=21415.238..21415.239 rows=0 loops=1)
         Output: id, tx_hash, tx_status, created_at
         Index Cond: (pool_transaction_entries.id > 15006000)
         Filter: (pool_transaction_entries.tx_status = 0)
         Rows Removed by Filter: 3556
 Query Identifier: 3330758434230110582
 Planning Time: 54.206 ms
 Execution Time: 21415.281 ms
(10 rows)

请你给我一个提示,如何创建索引或优化这一点?非常感谢!

EN

Stack Overflow用户

发布于 2022-11-07 18:13:06

你最好的索引是:

代码语言:javascript
运行
复制
CREATE INDEX X 
   ON pool_transaction_entries (tx_status, id) 
   INCLUDE (tx_hash, created_at);

因为:

  • tx_status =
  • id由>

查找

所以索引键必须是这样的顺序..。

INCLUDE子句用于避免索引查找后的表访问。普通索引不包含表的所有列,只包含键列。INCLUDE说,更多的列被添加到索引的叶页中,以具有覆盖索引。此技术自2005年起在Microsoft中添加,最近添加到PostGreSQL中以模拟.这种技术非常有效,因为只有一个对象,索引本身为什么涵盖所有查询子句(SELECT子句,WHERE子句,GROUP,WHERE子句,ORDER子句.)没有任何表访问

票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74345170

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档