Postgresql 中 FOUND_ROWS() 函数的等效项

发布于 2024-09-28 13:36:37 字数 630 浏览 3 评论 0原文

我正在我的应用程序中进行一些分页,使用 PostgreSQL 的标准 OFFSET 和 LIMIT 关键字一次从数据库返回 20 行。例如,要获取第 1 页:

SELECT stuff FROM table WHERE condition ORDER BY stuff OFFSET 0 LIMIT 20

应用程序要求我们还向用户显示记录总数。因此,显然,我可以通过发出单独的查询来获取总数:

SELECT COUNT(*) FROM table WHERE condition

但如果有大量行,那么这不是最佳解决方案。我注意到 MySQL 有一个非常有用的函数,称为 FOUND_ROWS(),它正是我正在寻找的:

http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function%5Ffound-rows

是否有等效的在 PostgreSQL 中?

I am doing some paging in my application, returning 20 rows from the database at a time using PostgreSQL's standard OFFSET and LIMIT keywords. For instance, to get page 1 page:

SELECT stuff FROM table WHERE condition ORDER BY stuff OFFSET 0 LIMIT 20

It is a requirement of the application that we also show to the user the total number of records. So, obviously, I can get the total by issuing a separate query:

SELECT COUNT(*) FROM table WHERE condition

But if there are a large number of rows then this is not an optimal solution. I notice that MySQL has a very useful function called FOUND_ROWS() that does exactly what I am looking for:

http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function%5Ffound-rows

Is there an equivalent in PostgreSQL?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

何止钟意 2024-10-05 13:36:37

PostgreSQL 拥有窗口函数已经有一段时间了,它可以用来做很多事情,包括在应用 LIMIT 之前计算行数。

基于上面的例子:

SELECT stuff,
       count(*) OVER() AS total_count
FROM table
WHERE condition
ORDER BY stuff OFFSET 40 LIMIT 20

PostgreSQL has had window functions for a while now which can be used to do many things including counting rows before LIMIT is applied.

Based on the example above:

SELECT stuff,
       count(*) OVER() AS total_count
FROM table
WHERE condition
ORDER BY stuff OFFSET 40 LIMIT 20
你在我安 2024-10-05 13:36:37
SELECT
    n_live_tup     
FROM
    pg_stat_user_tables     
WHERE 
    relname = 'table_Name';
SELECT
    n_live_tup     
FROM
    pg_stat_user_tables     
WHERE 
    relname = 'table_Name';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文