2017-04-02 64 views
0

我在postgres中編寫查詢以選擇包含更多註釋的帖子。PostgreSQL多重計數查詢性能

以下工作,但我想知道它是否會成爲許多職位的性能問題。

查詢

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

您可以使用連接而不是相關的子查詢。假設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; 
+0

在第二個例子中我得到這個錯誤: '的WHERE必須是boolean類型的參數,而不是鍵入integer' – pietrovismara

+0

@pietrovismara - 這是一個錯字。更新了答案。請立即嘗試 – GurV

+0

無論如何,比較你的第一個查詢和我的'EXPLAIN'結果,你的看起來好多了。這是因爲使用加入計數只能在匹配註釋而不是所有的註冊? – pietrovismara