views:

171

answers:

5

Welcome,

I'm wondering is it possible to reverse returned data in sorting "order by desc" but i want that data in reverse order.

For example, i got table with values

ID
1
2
3
4

And i do

Order by ID ASC LIMIT 3 I got

1
2
3

When i do Order by ID DESC limit 3 i get

4
3
2

I would like to have

3
2
1

So i would like to order by ASC but revers results. I was always doing this in PHP side using array_reverse, but today i want ask You. Maybye i'm wrong and i can do this just in Mysql. Regards

+3  A: 

You can fetch the first three rows using a subquery and then reverse the order of these rows in an outer query:

SELECT *
FROM
(
    SELECT *
    FROM yourtable
    ORDER BY ID
    LIMIT 3
) T1
ORDER BY ID DESC
Mark Byers
A: 

You could use an outer SELECT to reverse the order:

SELECT *
FROM (
    SELECT …
    ORDER BY id ASC
    LIMIT 3
) sub
ORDER BY id DESC
Gumbo
+6  A: 
SELECT * 
FROM (
  SELECT ... 
  FROM ... 
  ORDER BY ID ASC 
  LIMIT 3
) AS sq 
ORDER BY ID DESC
Mchl
That's work great.
marc
+2  A: 

Nope, you aren't wrong. There are no difference for any sensible amount of data. Array_reverse is all right.
That's not a thing you have to be concerned too much of. Just use whatever you like more - for readability or other subjective reasons

Col. Shrapnel
+1  A: 

You can do this with a sub query :

SELECT * FROM
    (SELECT * FROM myTable ORDER BY idMyTable LIMIT 0, 3) AS r
ORDER BY r.idMyTable DESC

Resources :

Colin Hebert