如果PostgreSQL count(*)总是很慢,如何分页复杂查询? [英] If PostgreSQL count(*) is always slow how to paginate complex queries?

查看:933
本文介绍了如果PostgreSQL count(*)总是很慢,如何分页复杂查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果PostgreSQL的 count(*)总是慢如何对复杂的查询进行分页?



只要在这种情况下,我们有很多页面(对于例如不同类别,过滤器等)。



如果 VACUUM / VACUUM ANALYZE / ANALYZE / VACUUM FULL 怎么办没有帮助吗?在Postgresql中使用 count(*)的最佳实践是什么?

解决方案

您是否阅读了该文章的标题?


请注意,以下文章仅适用于9.2之前的PostgreSQL版本。仅索引扫描现在已实现。


使用9.2,您通常会发现效果更好。阅读仅索引扫描Wiki页面以获取详细信息。



也就是说,在使用 LIMIT OFFSET 的旧版本上通常可以正常工作。如果您不介意任何变化,则可以使用表格统计信息来估算行数(因此也可以估算页数)。请参阅您已链接的文章中的估计行数



IMO始终使用 LIMIT OFFSET 进行分页是一种反模式。很多时候您可以重新定义分页代码,因此它使用 sort_column> last_seen_value为LIMIT 100 ,即避免了偏移量。有时这可能会导致很大的性能提升。


If PostgreSQL's count(*) is always slow how to paginate complex queries?

Making triggers doesn't seem to be a good solution as long as in this case we have a lot of pages (for example different categories, filters, etc).

What to do if VACUUM/VACUUM ANALYZE/ANALYZE/VACUUM FULL doesn't help? What are the best practices to use count(*) with postgresql?

解决方案

Did you read the heading on that article?

Note that the following article only applies to versions of PostgreSQL prior to 9.2. Index-only scans are now implemented.

Use 9.2 and you'll generally find you get much better results. Read the index-only scans wiki page for details.

That said, on older versions using LIMIT and OFFSET generally works fine. You can estimate rowcounts (and therefore pagecounts) using the table statistics if you don't mind a bit of variation. See "Estimating row count" in the article you already linked to.

Paginating using LIMIT and OFFSET is, IMO, an anti-pattern anyway. A lot of the time you can rephrase your pagination code so it uses sort_column > 'last_seen_value' LIMIT 100, i.e. it avoids the offset. This can sometimes result in very large performance gains.

这篇关于如果PostgreSQL count(*)总是很慢,如何分页复杂查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆