1

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?

3
  • 2
    If ID is unique then it wont orde by timeSent. Commented May 29, 2015 at 10:36
  • Do you want it by date ascending or descending? Not sure if there's a mistake in your post. (You ask by date descending but use ASC keyword in your query.) Commented May 29, 2015 at 10:39
  • try it ORDER BY timeSent ASC,ID DESC Commented May 29, 2015 at 10:47

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.