Wilber
Wilber

Reputation:

Query result reversing

I am using the following query to retrieve the last 10 results of my database, but I need them not to be in descending order. Is there anyway I can accomplish this with the query or do I need to handle it in php? Thanks for your help.

SELECT * FROM MSG ORDER BY id DESC LIMIT 0,10

Upvotes: 5

Views: 108

Answers (4)

Sterex
Sterex

Reputation: 1028

While using a nested query is one answer, I believe it is more optimum to execute two queries than a nested or a sub-query. Decreases the overhead - correct me if I'm wrong.

I'd suggest:

$row_offset = get_result("SELECT COUNT(*) FROM MSG;") - 10;

$rows = get_result("SELECT * FROM MSG LIMIT " . $row_offset . ", 10;");

Assuming (of course!) that get_results() is a custom function executing the query and returning the data from the table.

Upvotes: 1

jeroen
jeroen

Reputation: 91734

Apart from the mysql answers that are already there, a php solution would be to use array_reverse() on your original result set.

Upvotes: 3

Deepu S Nath
Deepu S Nath

Reputation: 1184

Please try the following to resolve your issue

SELECT * FROM (SELECT * FROM MSG ORDER BY id DESC LIMIT 10) AS RequiredLimit ORDER BY id ASC

Upvotes: 4

blueadept
blueadept

Reputation: 171

SELECT * FROM (SELECT * FROM MSG ORDER BY id DESC LIMIT 0,10) ORDER BY id -- should work

Upvotes: 4

Related Questions