分页:找出项目所在的页面(给定主键和排序顺序)

2024-04-15

假设我像这样进行分页:

SELECT article_id, 
       article_content 
FROM articles 
ORDER BY article_rating 
OFFSET (page - 1) * items_per_page 
LIMIT items_per_page;

我有一个索引(文章评级、文章 ID).

我的问题是:什么是最有效率的找出文章在哪个页面的方法,如果我

a) 知道article_id

b) 知道排序是 ORDER BY Article_Rating 吗?

它需要高效,因为我将经常执行此类查询。

如果它不仅能显示页码,还能显示该页面上的所有文章,那就更好了。

因此,举例来说,如果所有文章都按评分排序,并且每十篇文章都放在不同的页面上,我想找出 ID 为 839 的文章位于哪个页面上。

我正在使用 PostgreSQL 8.4(如果需要,我愿意更新)。

谢谢你!

EDIT:

正如下面的评论所指出的,我的查询可能应该如下所示:

SELECT article_id, 
       article_content 
FROM articles 
ORDER BY article_rating,
         article_id
OFFSET (page - 1) * items_per_page 
LIMIT items_per_page;

EDIT请参阅下面的第二个查询,它比第一个查询要好得多。

假设 Postgres 9.0 或更高版本,您必须使用窗口函数来获取每个项目的 row_number 。然后,将特定文章的 row_number 除以 items_per_page (和 round)以获得页码。唯一可用的效率改进是至少不查询即将到来的文章after那个有问题的人。所以你会得到这样的东西:

Select ceiling(rowNumber/items_per_page)
  from (
SELECT article_id
     , article_content 
     , row_number() over (order by article_rating, article_id)
       as rowNumber
  FROM articles 
 where article_rating <= (select article_rating
                            from articles
                           where article_id = 'xxxx' )
 ORDER BY article_rating,
          article_id
       ) x
 where article_id = 'xxxx'

EDIT回答评论中的问题。是的,我刚刚意识到有一种更好的方法可以做到这一点。通过运行 count(*) 我们只遍历索引。

Select ceiling(count(*)/items_per_page)
  FROM articles 
 where article_rating < (select article_rating
                           from articles
                          where article_id = 'xxxx' )
    or ( article_rating = (select article_rating
                           from articles
                          where article_id = 'xxxx' )
        and article_id <= 'xxxx')

通常我们不喜欢 WHERE 子句中的 OR 子句,因为它们会降低性能,但是这个应该非常安全,因为如果对article_ rating 建立索引,每个子句都应该是可优化的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

分页:找出项目所在的页面(给定主键和排序顺序) 的相关文章

随机推荐