简体   繁体   中英

MySQL query multiple column ordering

So, I've written a query which should grab 15 most recent results from the 'messages' table, but order results by date in descending direction. My current query is as follows:

SELECT * FROM messages 
    WHERE chatID = 1 
    ORDER BY ID DESC, timeSent ASC 
    LIMIT 15

As you can see, I am using the 'ID DESC' to get the 15 most recent results, but the 'timeSent ASC' isn't ordering the results in the order I wish.

How can I correct my query to achieve this?

First fetch the messages by ordering the ID then sort it according to timeSent . You can try this -

SELECT * FROM 
   (SELECT * FROM messages WHERE chatID = 1 ORDER BY ID DESC LIMIT 15) messages_ordered 
ORDER BY timeSent 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM