【问题标题】:Optimising postgresql query优化 postgresql 查询
【发布时间】:2020-08-14 15:17:14
【问题描述】:

我有这个查询,我喜欢这个查询相当慢:

select * from "cams" where 
 "bust" is not null and 
 "figure" is not null and 
 "age" is not null and 
 "hair" is not null and 
 "ethnicity" is not null  
  and "status" = 'online' and  
 "cams"."deleted_at" is null 
 order by ethnicity = 'white'  DESC, 
  age = 22 DESC, 
 (age >= 18 AND age <= 35) DESC, 
 bust = 'medium' DESC, 
 figure = 'petite' DESC, 
 hair = 'blonde' DESC 
 limit 10

解释分析输出

 Limit  (cost=10045.82..10045.84 rows=10 width=318) (actual time=754.187..754.190 rows=10 loops=1)
   ->  Sort  (cost=10045.82..10047.15 rows=532 width=318) (actual time=754.182..754.183 rows=10 loops=1)
         Sort Key: ((ethnicity = 'white'::ethnicity)) DESC, ((age = 22)) DESC, (((age >= 18) AND (age <= 35))) DESC, ((bust = 'medium'::bust)) DESC, ((figure = 'petite'::figure)) DESC, ((hair = 'blonde'::hair_color)) DESC
         Sort Method: top-N heapsort  Memory: 33kB
         ->  Bitmap Heap Scan on cams  (cost=1328.15..10034.32 rows=532 width=318) (actual time=580.008..745.590 rows=5092 loops=1)
               Recheck Cond: ((hair IS NOT NULL) AND (age IS NOT NULL) AND (status = 'online'::cam_status))
               Filter: ((bust IS NOT NULL) AND (figure IS NOT NULL) AND (ethnicity IS NOT NULL) AND (deleted_at IS NULL))
               Rows Removed by Filter: 2414
               Heap Blocks: exact=49643
               ->  Bitmap Index Scan on cams_online_rank_age  (cost=0.00..1328.02 rows=2406 width=0) (actual time=567.587..567.587 rows=4715231 loops=1)
                     Index Cond: ((hair IS NOT NULL) AND (age IS NOT NULL))
 Planning Time: 1.526 ms
 Execution Time: 754.464 ms

是否有一个索引可以加快速度(记住 order by 的值是动态的)?我在想一个关于胸围、身材、年龄、头发种族不为空的部分索引,并且 status = 'online' 但不确定要在哪一列上排名,因为顺序是动态的(我试图找到类似的帖子项目到某个项目)。

【问题讨论】:

    标签: sql postgresql query-optimization


    【解决方案1】:

    您唯一的希望是在(status, deleted_at) 上建立索引。这至少与where 子句中的相等条件相匹配。如果您知道另一列的 null 值比例很高,则可以将其作为第三个键。

    这可能会限制表的扫描。但是,性能可能更多地基于对order by 的排序而不是扫描表。

    【讨论】:

      猜你喜欢
      • 2014-06-13
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多