PostgreSQL多重计算查询性能

时间:2017-04-02 17:07:54

标签: sql postgresql count sqlperformance

我正在postgres中编写一个查询来选择包含更多评论的帖子。

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

查询

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

我可以采取哪些措施来改善此查询性能,还是可以的?

1 个答案:

答案 0 :(得分:1)

您可以使用join而不是相关子查询。假设id是帖子表中的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;