sql - Postgres 在与 Order By 一起使用时执行序列扫描

标签 sql postgresql indexing

select
    thread.id,
    thread.last_modified,
    count(*) as count
from
    thread 
inner join
    comment 
        on thread.id=comment.thread_id 
group by
    thread.id 
    limit 20

此查询将按预期使用索引扫描 enter image description here

但是现在如果我将 order by 添加到查询中:

select
    thread.id,
    thread.last_modified,
    count(*) as count
from
    thread 
inner join
    comment 
        on thread.id=comment.thread_id 
group by
    thread.id 
order by thread.last_modified
    limit 20

Postgres 将对 commentthread 执行 2 seq 扫描,如下所示: enter image description here

即使我在 lastModified 上有一个索引:

select thread.id
from thread
order by last_modified
limit 10

enter image description here

那么我的查询有什么问题吗?

最佳答案

第一个查询只需查找前 20 个线程的评论,而第二个查询必须选择所有 个线程的评论。顺序扫描是最有效的方法。

如果将 LIMIT 放入 FROM 子句中的子查询中,则可以改进查询:

... FROM (SELECT id, last_modified
         FROM thread
         ORDER BY last_modified LIMIT 20) thread

关于sql - Postgres 在与 Order By 一起使用时执行序列扫描,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51492114/

相关文章:

sql-server - Sql Server 索引包含主键吗?

javascript - 如何比较数组中的每个元素并将具有相同数据的元素分组(在我的例子中是日期)? JavaScript

postgresql - 如何强制 postgres 9.4 更可预测地命中 gin 全文索引?查看我的查询计划错误

sql - Group By 语句作为列

sql - 如何删除FK和所有从属表条目?

SQL:计数高于组平均值的值

json - Elixir - 从 2 个集合创建 JSON 对象

MySQL 解释 SERIALIZABLE 比 PostgreSQL 更轻松。这是对的吗?

PHP 许多包含的文件

SQL约束更新问题