2

I do know how to access last N records from the table i.e,

SELECT * FROM table_name ORDER BY auto_incremented_id DESC LIMIT N;

There are N records means and table records keep incrementing every day, each record having unique serial ID from 1 to N. now i want to retrieve 10 records of last N-10 rows.

please consider the example

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

How do i can retrieve N-2 to N-M rows

The solution required for an website - 1st page displays last 10 records, 2nd Page displays last next 10 records from the reverse except rows are displayed in first page and it goes on up to 1st record of the table.

4

2 回答 2

3

For dynamically limiting the output rows you can use inline views (as MySQL doesn't support common table expressions using WITH clause). An example code is as follows:

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.

于 2013-03-30T17:03:41.040 回答
3

you can play with ordering and your limit conditions

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

assuming as you say a paging size of 10

first page:

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

second page:

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

third page:

SELECT * from (SELECT * from table_name ORDER BY auto_incremented_id DESC LIMIT 30) as temp ORDER BY auto_incremented_id ASC LIMIT 10;
于 2013-03-30T17:24:08.603 回答