PostgreSQL 多次计数查询性能

PostgreSQL multiple counts query performance

我正在 postgres 中编写查询,以 select 有更多评论的帖子。

以下有效,但我想知道它是否会成为许多帖子的性能问题。

查询:

SELECT 
    po.*, 
    (SELECT count(id) FROM comments WHERE post_id = po.id) AS comments_count
    FROM posts AS po
    ORDER BY comments_count DESC
    LIMIT 10;

结果:

id   title  body  comments_count
2    Foo    Bar   5
1    Click  Bait  4

我可以做些什么来提高这个查询性能吗?

您可以使用连接而不是相关子查询。假设id在帖子table中PK:

select p.*,
    count(c.id) as comments_count
from posts p join comments c on p.id = c.post_id
group by p.id
order by comments_count desc limit 10;

select p.*,
    c.comments_count
from posts p
join (
    select post_id,
        count(id) as comments_count
    from comments
    order by comments_count desc LIMIT 10
    ) c on p.id = c.post_id;