views:

68

answers:

3

Hello I want to run a query to get the last five records from a table, but in reverse order. Currently I have:

$query = "SELECT * FROM Table ORDER BY id DESC LIMIT 5";

which isn't quite what I want.

For example if the last five records are

15 16 17 18 19

I want them returned as

15 16 17 18 19

Not 19 18 17 16 15 which is what the above does.

How do I achieve this? If I change DESC to ASC it gives 1 2 3 4 5 so that doesn't work either.

+4  A: 

Try a sub query:

SELECT *
FROM (SELECT * FROM Table ORDER BY id DESC LIMIT 5) AS tmp
ORDER BY id ASC
Gumbo
MySQL (at least) requires an alias. If you run this query, you will probably see this error: ERROR 1248 (42000): Every derived table must have its own alias
Suppressingfire
@Suppressingfire: Ah, thanks!
Gumbo
So how do I do it?None of these work, I get mysql errors when I try and output the data.
David Willis
@David Willis: It works for me. What error do you get?
Gumbo
Sorry it works perfectly, my mistake!Very good!!
David Willis
+1  A: 

You can use a sub-select to do that:

SELECT * FROM (SELECT * FROM table ORDER BY id DESC LIMIT 5) AS t ORDER BY id
Greg
doesn't work, sorry.
David Willis
What error do you get?
Greg
Are you using a realllllly old version of MySQL perhaps?
Greg
+1  A: 

SELECT * FROM (SELECT * FROM Table ORDER BY id DESC LIMIT 5) T1 ORDER BY id ASC;

Jerry Fernholz