Andrew Ward Andrew Ward - 2 months ago 8
SQL Question

Order by DESC reverse result

I'm retrieving some data in sql order by DESC, I then want to reverse the result. I was doing this by pushing the data into an array and then using array_reverse but am finding it's quite taxing on CPU time and would like to simply use the correct SQL query.

I've looked at this thread http://stackoverflow.com/questions/12534248/sql-server-reverse-order-after-using-desc#= but cannot seem to make it work with my query.

SELECT live.message,
live.sender,
live.sdate,
users.online
FROM live, users
WHERE users.username = live.sender
ORDER BY live.id DESC
LIMIT 15

Answer

You could wrap your query with another query and order by with asc. Since you want to order by live.id, you must include it in the inner query so the outer one can sort by it:

SELECT   message, sender, sdate, online 
FROM     (SELECT   live.message, live.sender, live.sdate, users.online, live.id 
          FROM     live, users
          WHERE    users.username = live.sender 
          ORDER BY live.id DESC 
          LIMIT    15) t
ORDER BY id ASC
Comments