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 I 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 SQL Server reverse order after using desc , but I 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
You can place your query into a subquery and then reverse the order:
SELECT t.message,
t.sender,
t.sdate,
t.online
FROM
(
SELECT live.id,
live.message,
live.sender,
live.sdate,
users.online
FROM live
INNER JOIN users
ON users.username = live.sender
ORDER BY live.id DESC
LIMIT 15
) t
ORDER BY t.id ASC
You'll notice that I replaced your implicit JOIN
with an explicit INNER JOIN
. It is generally considered undesirable to use commas in the FROM
clause (qv the ANSI-92 standard) because it makes the query harder to read.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.