MySQL 按日期排序然后按 ID 排序

MySQL order by date then order by an id

我试图对我的查询结果进行排序,以便具有最新日期的行在结果集中排在第一位。我还需要查询将所有 conversation_id 组合在一起。

这是我当前的查询:

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;

排序不正确。

我使用上面的查询得到这个 table:http://imgur.com/QLoEj6H

我需要的是 conversation_id 2 组位于顶部。将查询末尾的 ORDER BY 更改为 DESC 不适用于 table 中的所有值。

子查询除了减慢查询速度外什么都不做。

您似乎希望按对话排序,但最近的对话排在第一位。如果是这样,您需要使用额外的 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;

尝试在没有子查询的情况下使用 ORDER BY conversation_id DESC, sent_date DESC

这将按 conversation_id 的降序检索结果,如果出现平局,将按时间降序排列。 (如果这就是您要找的)

在朋友的帮助下和 Gordon Linoff 的回答下弄明白了。以下是可用的代码:

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;