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
但是现在如果我将 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 将对 comment
和 thread
执行 2 seq 扫描,如下所示:
即使我在 lastModified
上有一个索引:
select thread.id
from thread
order by last_modified
limit 10
那么我的查询有什么问题吗?
最佳答案
第一个查询只需查找前 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/