kennyjwilli
kennyjwilli

Reputation: 193

MySQL order by date then order by an id

I am trying to order my query results so that the row with the newest date is first in the result set. I also need for the query to then group all the conversation_ids together.

Here is my current query:

SELECT conv.conversation_id, conv.user_id, conv.contact_id, msg.message_id, msg.message, msg.sent_date
FROM (SELECT * FROM message ORDER BY sent_date DESC) as msg
LEFT JOIN conversation AS conv
ON conv.contact_id = msg.contact_id
WHERE user_id = 24
ORDER BY conversation_id;

It does not sort correctly.

I get this table using the above query: https://i.sstatic.net/IGmVo.jpg

What I need is for the group with conversation_id 2 to be at the top. Changing the ORDER BY at the end of the query to be DESC will not work for all values in the tables.

Upvotes: 1

Views: 4263

Answers (3)

Gordon Linoff
Gordon Linoff

Reputation: 1269933

The subquery does nothing, except slow down your query.

You seem to want things ordered by conversations, but by the most recent conversation first. If so, you need to bring that information into the query using an additional join:

SELECT conv.conversation_id, conv.user_id, conv.contact_id,
       msg.message_id, msg.message, msg.sent_date
FROM message msg LEFT JOIN
     conversation conv
     ON conv.contact_id = msg.contact_id LEFT JOIN
     (SELECT conversation_id, MAX(sent_date) as max_ent_date
      FROM message
      GROUP BY conversation_id
     ) mmax
     ON mmax.conversation_id = m.conversation_id
WHERE user_id = 24
ORDER BY mmax.max_sent_date desc, m.conversation_id;

Upvotes: 1

kennyjwilli
kennyjwilli

Reputation: 193

Figured it out with the help of a friend and Gordon Linoff's answer. Below is the code that will work:

SELECT conv.conversation_id, conv.user_id, conv.contact_id,
       msg.message_id, msg.message, msg.sent_date
FROM message msg LEFT JOIN
     conversation conv
     ON conv.contact_id = msg.contact_id LEFT JOIN
     (SELECT conversation_id, MAX(sent_date) as max_msg_sent_date
      FROM message
      GROUP BY conversation_id
     ) mmax
     ON mmax.conversation_id = msg.conversation_id
WHERE user_id = 24
ORDER BY max_msg_sent_date desc, msg.conversation_id, msg.sent_date DESC;

Upvotes: 1

shikharsaxena30
shikharsaxena30

Reputation: 155

Try using ORDER BY conversation_id DESC, sent_date DESC without the sub-query.

This will retrieve results in the decreasing order of conversation_id and in case of ties, will arrange them in descending order of their time. (If that is what you're looking for)

Upvotes: 0

Related Questions