views:

29

answers:

4

Hi, i was wondering if there was an easy way with just an sql statement to return the last three results in the table but in that order i.e. if there are a hundered results it would return in the order of 98, 99, 100 not simply ordering by id DESC and limit 3 which would return in order 100, 99, 98

Any help much appreciated.

p.s. in this instance, lets say I don't know the amount of results and don't really want to send 2 sql requests just to find the amount ( for any OFFSET answers ).

+3  A: 

One way would be to use DESC and then just sort them again:

SELECT * FROM (SELECT * FROM some_table ORDER BY id DESC LIMIT 3) a ORDER BY id
Lukáš Lalinský
all very similar answers but thank you all, cheers Lukas
Phil Jackson
getting err _error_ 1 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY ID DESC LIMIT 3) AS T ORDER BY TIME_STAMP' at line 1
Phil Jackson
Post your query. Also, didn't you want to `ORDER BY TIME_STAMP DESC` in the inner query?
Lukáš Lalinský
my fault, never mind!
Phil Jackson
thanks anyway!!
Phil Jackson
A: 
Select * 
FROM (SELECT * FROM yourTABLE ORDER BY ID DESC LIMIT 0,3) as TempTable ORDER BY ID
Taz
+1  A: 

Two options, I guess.

  1. You could use DESC to return them in reverse order as you stated, and just reverse the order again in your application code. This is potentially the most efficient, as you can do it in a single query and it can potentially only need to read three rows of an index.

  2. You can first find out the number of results in the table, then do a LIMIT <results-3>, 3

thomasrutter
A: 

Is it okay if you just flip it back to the original order?

SELECT * FROM (SELECT * FROM SOMETABLE ORDER BY ID DESC LIMIT 3) AS T ORDER BY ID;
brool