【问题标题】:PostgreSQL multiple counts query performancePostgreSQL 多重计数查询性能
【发布时间】:2017-04-02 17:07:53
【问题描述】:

我正在 postgres 中编写查询以选择具有更多 cmets 的帖子。

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

查询

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

我可以做些什么来提高此查询性能还是可以?

【问题讨论】:

    标签: sql postgresql count sqlperformance


    【解决方案1】:

    您可以使用联接而不是相关子查询。假设 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;
    

    【讨论】:

    • 在第二个例子中我得到这个错误:argument of WHERE must be type boolean, not type integer
    • @pietrovismara - 这是一个错字。更新了答案。请立即尝试
    • 无论如何,比较你的第一个查询和我的EXPLAIN 结果,你的看起来好多了。这是因为使用 join 计数只在匹配的 cmets 而不是全部上完成?
    • 这是因为相关子查询。它的复杂度是O(n^2)
    猜你喜欢
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2021-08-03
    • 2013-02-17
    • 2013-09-22
    • 1970-01-01
    相关资源
    最近更新 更多