【问题标题】:Mysql pagination without offset没有偏移量的Mysql分页
【发布时间】:2014-11-16 23:12:31
【问题描述】:

假设我有一张包含这些数据的表格:

我想通过 createdAt 列 DESC 和 id 列 DESC 来订购它

select id, createdAt from post order by createdAt desc, id desc

现在看起来像这样:

我想用每页 2 个项目对其进行分页,出于性能原因,我不想使用 offset,只使用 limit

select id, createdAt from post order by createdAt desc, id desc limit 2

要获得接下来的 2 个项目,我使用此查询:

SELECT id, createdAt FROM post  WHERE createdAt <= '2014-11-16 09:11:03' AND (id < '15' OR createdAt < '2014-11-16 09:11:03') ORDER BY createdAt DESC, id DESC LIMIT 2

我可以这样继续下去。获取最后一项的createdAtid 然后将其用于next 页面查询。

但我试图制定previous page 查询将近两天,但还没有找到方法。

这是我已经尝试过的:

从当前结果中获取第一项(而不是最后一项)使用它的 idcreatedAt 字段并反转查询中的条件 (createdAt &gt;=, id &gt;, created at &gt;)。但是这个查询总是给我前两个结果(这是正常的,因为提供这个条件的行是前两个)。

我已经没有想法了。我需要帮助。谢谢。

【问题讨论】:

  • 实际上,数据集比这大得多吗?
  • 是的,它充满了数百万行的日志分析数据。
  • 偏移量有什么问题?
  • 偏移会在几页后减慢速度。更多信息:i.imgur.com/Q8ZRKPs.jpg 和 slideshare.net/Eweaver/efficient-pagination-using-mysql
  • 我很想问问 Rick James(又名 superfreak)。

标签: mysql sql pagination


【解决方案1】:

您可以按升序排列以获得正确的记录:

SELECT id, createdAt 
  FROM post 
 WHERE createdAt >= '2014-11-16 09:11:03' 
   AND (id > '15' OR createdAt > '2014-11-16 09:11:03') ORDER BY createdAt ASC, id ASC
LIMIT 2

在显示结果集时进行反向排序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 2013-08-24
    • 1970-01-01
    • 2021-10-14
    • 2011-12-07
    • 1970-01-01
    • 2011-04-01
    • 2015-03-15
    相关资源
    最近更新 更多