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
那我的查询出了什么问题?
答案 0 :(得分:2)
第一个查询只需要找到对前20个线程的注释,而第二个查询必须为 all 个线程选择注释。顺序扫描是最有效的方法。
如果将LIMIT
放在FROM
子句的子选择中,则可以改进查询:
... FROM (SELECT id, last_modified
FROM thread
ORDER BY last_modified LIMIT 20) thread