sql - 关于PostgreSQL性能的两个问题

标签 sql performance postgresql pagination

1) 在 PostgreSQL 中实现分页的最佳方式是什么?

假设我们需要实现分页。最简单的查询是 select * from MY_TABLE order by date_field DESC limit 10 offset 20据我所知,我们这里有 2 个问题:如果日期可能有重复值,每次运行此查询都可能返回不同的结果,并且偏移值越大,查询运行的时间就越长。我们必须提供额外的列,即 date_field_index:

--date_field--date_field_index--
  12-01-2012     1
  12-01-2012     2
  14-01-2012     1
  16-01-2012     1
--------------------------------

现在我们可以这样写

create index MY_INDEX on MY_TABLE (date_field, date_field_index);
select * from MY_TABLE where date_field=<last_page_date and not (date_field_index>=last_page_date_index and date_field=last+page_date) order by date_field DESC, date_field_index DESC limit 20;

..因此使用 where 子句和相应的索引而不是偏移量。好的,现在是问题:

1) 这是改进初始查询的最佳方法吗? 2) 我们如何填充 date_field_index 字段?我们必须为此提供一些触发条件吗? 3) 我们不应该在 Postgres 中使用 RowNumber() 函数,因为它们不使用索引,因此非常慢。是否正确?

2) 为什么连接索引中的列顺序不影响查询的性能?

我的测量表明,在使用连接索引(由 2 个或更多列组成的索引)进行搜索时,如果我们将最具选择性的列放在首位或将其放在末尾,则没有区别。为什么?如果我们将最有选择性的列放在首位 - 我们会遍历较短范围的已找到行,这应该会对性能产生影响。我说得对吗?

最佳答案

使用主键解开而不是date_field_index列。否则解释为什么这不是一个选项。

order by date_field DESC, "primary_key_column(s)" DESC

具有最唯一列的组合索引性能最好,但在以下情况下不会使用:

  • 不同的值超过表格的百分之几
  • 没有足够的行使其值得
  • 日期范围不够小

explain my_query 的输出是什么?

关于sql - 关于PostgreSQL性能的两个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15766507/

相关文章:

php - 从sql表中选择随机行时如何防止选择已删除的ID

python - Numpy-native "nested-for-like"结构

ruby - `clear_transaction_record_state' : undefined method `[]' for nil:NilClass when creating a record Ruby

postgresql - 无法连接到我在 Azure 中新创建的 postgresql 服务器

mysql - 多重连接过滤

sql - 根据使用的 where 子句对正确的列建立索引

java - 与 "iteration is linear in the sum of the number of entries and the number of buckets"混淆

node.js - 嵌套的 Lodash ForEach

database - 相当于postgresql的非开源数据库

sql - 返回 NEWSEQUENTIALID() 作为输出参数