Postgresql 需要减少postgres中的查询优化时间

Postgresql 需要减少postgres中的查询优化时间,postgresql,query-optimization,query-performance,postgresql-10,Postgresql,Query Optimization,Query Performance,Postgresql 10,用例:需要在表中找到特定id的索引和totalCount 我有一个表annu details,它有6000万条记录,根据where条件,我需要检索这些行以及该id的索引 查询: with a as ( select an.id, row_number() over (partition by created_at) as rn from annotation an where ( an.layer_id = '47afb169-aed2-4378-ab13-8978362

用例:需要在表中找到特定id的索引和totalCount

我有一个表annu details,它有6000万条记录,根据where条件,我需要检索这些行以及该id的索引

查询:

with a as (
    select an.id, row_number() over (partition by created_at) as rn
    from annotation an
    where ( an.layer_id = '47afb169-aed2-4378-ab13-897836275da3' or an.job_id = '' or an.task_id = '') and
     an.category_id in (10019)

) select (select count(1) from a ) as totalCount , rn-1 as index from a where a.id= '47afb169-aed2-4378-ab13-897836275da3_a93f0758-8fe0-4c76-992f-0be17e5618bf_484484101';
输出:

totalCount index
1797124,1791143
执行时间:5秒487毫秒

解释和分析

CTE扫描a(成本=872778.54..907545.00行=7722宽度=16)(实际时间=5734.572..5735.989行=1圈=1)
过滤器:((id)::text='47afb169-aed2-4378-ab13-897836275da3_a93f0758-8fe0-4c76-992f-0be17e5618bf_484484101':text)
被筛选器删除的行:1797123
CTE a
->WindowAgg(成本=0.68..838031.38行=1544318宽度=97)(实际时间=133.660..3831.998行=1797124循环=1)
->仅使用注释an上的测试索引测试2进行索引扫描(成本=0.68..814866.61行=1544318宽度=89)(实际时间=133.647..2660.009行=1797124循环=1)
索引条件:(类别id=10019)
筛选器:((层id)::text='47afb169-aed2-4378-ab13-897836275da3'::text)或((作业id::text='':text='':text)或((任务id::text='':text))
被筛选器删除的行:3773007
堆取数:101650
初始计划2(返回$1)
->聚合(成本=34747.15..34747.17行=1宽度=8)(实际时间=2397.391..2397.392行=1圈=1)
->a_1上的CTE扫描(成本=0.00..30886.36行=1544318宽度=0)(实际时间=0.017..2156.210行=1797124圈=1)
计划时间:0.487毫秒
执行时间:5771.080毫秒
索引:

CREATE INDEX test_index_test_2 ON public.annotation USING btree (category_id,created_at,layer_id,job_id,task_id,id);
从应用程序中,我们将传递作业id或任务id或层id,其余2将作为空传递

需要帮助优化查询以在2秒内获得响应


查询计划:

而不是使用as,used temp table,下面是供参考的查询:
count(1)
实际上比
count(*)慢,但我怀疑它在这里有什么区别。如果在CTE内部使用
count(*)over()
而不是在外部查询中使用它会怎么样?顺便说一句:
row\u number()
没有一个
order by
通常是没有意义的。Hi@a\u horse\u没有名字,按照建议进行了更新,但在同一时间查询对我来说没有意义。如果你解释了目的,让我明白,我可以试着重写它。作为第一次尝试,用户可以在
FROM
子句中创建子查询,而不是CTE。