我有一张桌子,它有这些栏:
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_status按equal查询,id按“大于”查询。我的SQL查询是:
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;我发现它很慢!
这是分析结果:
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)请你给我一个提示,如何创建索引或优化这一点?非常感谢!
发布于 2022-11-07 18:13:06
你最好的索引是:
CREATE INDEX X
ON pool_transaction_entries (tx_status, id)
INCLUDE (tx_hash, created_at);因为:
查找
所以索引键必须是这样的顺序..。
INCLUDE子句用于避免索引查找后的表访问。普通索引不包含表的所有列,只包含键列。INCLUDE说,更多的列被添加到索引的叶页中,以具有覆盖索引。此技术自2005年起在Microsoft中添加,最近添加到PostGreSQL中以模拟.这种技术非常有效,因为只有一个对象,索引本身为什么涵盖所有查询子句(SELECT子句,WHERE子句,GROUP,WHERE子句,ORDER子句.)没有任何表访问
发布于 2022-11-08 04:11:32
谢谢@a_horse_with_no_name,这个答案来自他:
just create an index on (tx_status, id)https://stackoverflow.com/questions/74345170
复制相似问题