与Order By一起使用时,Postgres执行seq扫描

时间:2018-07-24 06:45:02

标签: 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

那我的查询出了什么问题?

1 个答案:

答案 0 :(得分:2)

第一个查询只需要找到对前20个线程的注释,而第二个查询必须为 all 个线程选择注释。顺序扫描是最有效的方法。

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

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