简体   繁体   中英

How to select the last n row in MySQL?

with this code I select the first 30 row of the table:

SELECT * FROM `table` LIMIT 0 , 30

But how to select the last 30, without changing the order?

It looks like everyone is missing this part:

But how to select the last 30, without changing the order?

First of all, clearly there is no order in the query provided. Assuming the order is ascending on some field this would be the query @DannyFox meant:

SELECT * FROM T
ORDER BY val
LIMIT 0 , 30

Now imagine we have simplified data, such as a, b, c, d, e and that we want only 3 rows instead of 30:

SELECT * FROM T
ORDER BY val
LIMIT 3

If this returns: a, b, c, d, e in each row, then he would expect to get c, d, e in that order. The query everyone is providing:

SELECT * FROM T
ORDER BY val desc
LIMIT 3

Would return e, d, c . The problem with this is that it's actually changing the original order, and the OP say he didn't want to change the order. So technically, the query that would result in c, d, e is:

select * from (
  select * from t
  order by val desc
  limit 3
) s
order by val

Which actually changes the order twice, getting the original order back.

Since you are trying to avoid ordering, then the solution would be to apply it twice.

 SELECT * 
   FROM (
            SELECT * 
              FROM `table_name` 
          ORDER BY `column_name` DESC -- maybe id?
             LIMIT 0, 30
         ) `table_aliase`
ORDER BY `column_name` ASC

First you need to specify an order:

SELECT * FROM table
ORDER BY some_id ASC -- ascending order
LIMIT 30

If that query returns the first 30 columns, this one will return the last 30:

SELECT * FROM table
ORDER BY some_id DESC -- descending order
LIMIT 30

如果你有一个自动增量键/列,比如id那么这是一个例子

SELECT * FROM `table` ORDER BY id DESC LIMIT 0 , 30;

也许这会起作用: select * from table WHERE id > ((SELECT MAX(id) from table) - 30);

Nothing is said about an order, so you can not use ORDER BY. There is a way to get records from a given point, but for that you need to know how many records there are, then use this counted value to provide the limits

SELECT COUNT(*) AS counted FROM table

SELECT * FROM table LIMIT (counted-30),30

Here's my method used with PHP:

$query = "SELECT * FROM table ORDER BY id DESC LIMIT 3";
$res = mysql_query($query);
$results = array();
while($row = mysql_fetch_assoc($res)){
     $results = $row[field];
}
// Back to original order based from DB
$results = array_reverse(results);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM