sql - 下限 LIMIT/高 OFFSET 的成本非常高

标签 sql performance postgresql explain

我有一个非常大的产品表。我需要选择几个偏移量非常高的产品(下面的示例)。 Postgresql 索引和性能手册建议在 ORDER BY + 最终条件使用的列上创建索引。一切都是桃色的,没有使用任何种类。但对于高偏移值,LIMIT 的成本非常高。任何人都知道这可能是什么原因造成的?

以下查询可以运行几分钟。

Indexes:
"product_slugs_pkey" PRIMARY KEY, btree (id)
"index_for_listing_by_default_active" btree (priority DESC, name, active)
"index_for_listing_by_name_active" btree (name, active)
"index_for_listing_by_price_active" btree (master_price, active)
"product_slugs_product_id" btree (product_id)

EXPLAIN SELECT * FROM "product_slugs" WHERE ("product_slugs"."active" = 1) ORDER BY product_slugs.name ASC LIMIT 10 OFFSET 14859;
                                                       QUERY PLAN                                                        
-------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=26571.55..26589.43 rows=10 width=1433)
   ->  Index Scan using index_for_listing_by_name_active on product_slugs  (cost=0.00..290770.61 rows=162601 width=1433)
         Index Cond: (active = 1)
(3 rows)

最佳答案

此处的 index_for_listing_by_name_active 索引不会有太大帮助,因为结果集中的产品在索引中不一定是连续的。尝试仅在那些活跃的产品上按名称创建条件索引:

CREATE INDEX index_for_listing_active_by_name
  ON product_slugs (name)
  WHERE product_slugs.active = 1;

关于sql - 下限 LIMIT/高 OFFSET 的成本非常高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4729677/

相关文章:

sql - 如何在查询中使用 (func()).* 语法避免多个函数求值?

postgresql - postgresql 中的字符串匹配模式

arrays - 在数组子对象上创建 Postgres JSONB 索引

php - 如果我只想要一个计数,我应该选择哪些列

Windows Phone 7 中的性能监控(电源和 FPS)

php - 在 PHP 中加速字符串搜索

sql - Oracle 数字字符串列和索引

mysql - 如何编写查询或过程

sql - 如何在 SQL Server 中对多个列的值求和

SQL在不使用union all函数的情况下在select语句中重复主键行