简体   繁体   中英

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_id s 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: http://imgur.com/QLoEj6H

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.

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;

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;

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)

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