Postgresql对两个索引组合的慢速查询
我有一个包含约1亿条记录和以下索引的表:Postgresql对两个索引组合的慢速查询,sql,postgresql,indexing,Sql,Postgresql,Indexing,我有一个包含约1亿条记录和以下索引的表: Column | Type | Modifiers | Storage | ---------------------+--------------------------+------------------------------------------------------------+----------+--------------+------------- id
Column | Type | Modifiers | Storage |
---------------------+--------------------------+------------------------------------------------------------+----------+--------------+-------------
id | integer | ... pk ...| plain |
url | character varying(500) | not null | extended |
description | text | | extended |
domain_id | integer | | plain |
index_status | integer | not null | plain |
索引:
- “mytable_pkey”主键,btree(id)
- “mytable\u url\u key”唯一约束,btree(url)
- “mytable_662cbf12”B树(域id)
- “mytable\u id\u idx”b树(id),其中索引\u状态=0
index\u status=0
索引,因为我想用以下内容查询表:
select *
from mytable
where index_status = 0
limit 1000;
它工作得很好,但现在我也想这样提问:
select *
from mytable
where index_status = 0 and domain_id = 233
limit 1000;
如您所见,我现在使用两个索引查询我的数据库,它工作得很好,因为我与域id
相关的记录大约为50000
,所以它查询它们的速度相当快(大约1s
)
但是现在我有一个与域id
相关的记录,大约有300000个
记录,大约需要10分钟
如果两个字段都建立了索引,怎么可能呢?我应该做些什么来加速这种查询?是否要创建新索引?您可以在多个列上创建筛选索引:
create index idx_mytable_3 on mytable(domain_id, id) where index_status = 0;
您可以用此表替换mytable\u id\u idx
注意:使用limit
而不使用order by
是可疑的。如果您希望在id
order中显示结果,则应明确包括orderbyid
。我查询它们并更改索引状态
,以便下次获得新的结果。