"Order by desc" in reverse order?
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
SELECT *
FROM (
SELECT ...
FROM ...
ORDER BY ID ASC
LIMIT 3
) AS sq
ORDER BY ID DESC
Think of it as working in two steps. First it executes the inner query: selects 3 records with lowest IDs. Then in the outer query it sorts them in descending order.
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
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
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 :
- Mysql - Subqueries
You could use an outer SELECT
to reverse the order:
SELECT *
FROM (
SELECT …
ORDER BY id ASC
LIMIT 3
) sub
ORDER BY id DESC
精彩评论