访问MySQL中的最后N-m条记录

时间:2013-03-30 16:57:47

标签: mysql sql

我知道如何从表中访问最后N条记录,即

SELECT * FROM table_name ORDER BY auto_incremented_id DESC LIMIT N;

有N个记录表和表记录每天都在递增,每个记录的唯一序列号从1到N.   现在我想检索最后N-10行的10条记录。

请考虑示例

  Record 1
  Record 2
  Record 3
  Record 4
  Record 5
  Record 6
  Record N-M
  Record N-2
  Record N-1
  Record N

如何检索 N-2到N-M

网站所需的解决方案 - 第一页面显示最后10条记录,第二页面显示最后10条相反的记录,除了行显示在第一页和它继续到桌子的第一个记录。

2 个答案:

答案 0 :(得分:3)

为了动态限制输出行,您可以使用内联视图(因为MySQL不支持使用WITH子句的公用表表达式)。示例代码如下:

SELECT *
  FROM (SELECT id, name
               , @i := @i + 1 as result
          FROM table_name
               , (select @i := 0) temp
      ORDER BY id) v
  CROSS JOIN (SELECT COUNT(id) AS M FROM table_name) w
 WHERE result BETWEEN w.m-2 AND w.m;

Fiddle

答案 1 :(得分:3)

您可以参与订购和限制条件

SELECT * from (SELECT * from table_name ORDER BY auto_incremented_id DESC LIMIT N) as temp ORDER BY auto_incremented_id ASC LIMIT M

假设您说的分页大小为10

第一页:

SELECT * from as temp ORDER BY auto_incremented_id DESC LIMIT 10;

第二页:

SELECT * from (SELECT * from table_name ORDER BY auto_incremented_id DESC LIMIT 20) as temp ORDER BY auto_incremented_id ASC LIMIT 10;

第三页:

SELECT * from (SELECT * from table_name ORDER BY auto_incremented_id DESC LIMIT 30) as temp ORDER BY auto_incremented_id ASC LIMIT 10;