正确排序 MySQL- 结果(可能需要一个子查询)

Sort MySQL-Result correctly (Probably need a sub-query)

我想创建一个消息系统,用户可以在其中互相发送消息。它应该像 Facebook 一样基于线程。所以每个用户都应该只与另一个用户在一个特定的消息线程中。

所有消息的主要概述未按我希望的那样工作。它仅显示线程的最旧(第一个)消息文本和日期,并且不按发送的最新消息排序。

这是我的 SELECT-Statement,我想我需要在某处进行子查询以让它按最新日期和文本排序,但我对此不熟悉,也不知道放在哪里以及如何放?

所以基本上我只希望消息线程按收到的最新消息排序,显示特定线程的最新文本和日期。

    $menu = mysql_query("SELECT 
t.`id`, t.`creator_uid`,
c.`uid` AS content_uid, c.`text`, c.`date` AS content_date,
a.`status`, a.`date` AS assign_date,
CASE 
WHEN t.`creator_uid`='".sInput($_SESSION['uid'])."' THEN `receiver_uid`
WHEN t.`receiver_uid`='".sInput($_SESSION['uid'])."' THEN `creator_uid`
END AS uid
FROM `messages_content` c
LEFT JOIN `messages_thread` t ON t.`id` = c.`thread_id`
LEFT JOIN `messages_assign` a ON a.`id` = t.`id`
WHERE 
t.`creator_uid`='".sInput($_SESSION['uid'])."' 
OR 
t.`receiver_uid`='".sInput($_SESSION['uid'])."' 
GROUP BY t.`id` 
ORDER BY c.`id` DESC") or die (mysql_error());

MySQL数据库结构:

messages_assign: id,uid,thread_id,status,date

messages_content: id,uid,thread_id,text,date

messages_thread: id,creator_uid,receiver_uid

您需要加入执行以下操作的子查询:

SELECT select thread_id, MAX(date) as latest_post_date
FROM messages_contents
GROUP BY thread_id

然后按latest_post_date

排序
$menu = mysql_query("SELECT 
    t.`id`, t.`creator_uid`,
    c.`uid` AS content_uid, c.`text`, c.`date` AS content_date,
    a.`status`, a.`date` AS assign_date,
    CASE 
    WHEN t.`creator_uid`='".sInput($_SESSION['uid'])."' THEN `receiver_uid`
    WHEN t.`receiver_uid`='".sInput($_SESSION['uid'])."' THEN `creator_uid`
    END AS uid
FROM `messages_content` c
LEFT JOIN `messages_thread` t ON t.`id` = c.`thread_id`
LEFT JOIN `messages_assign` a ON a.`id` = t.`id`
LEFT JOIN (SELECT thread_id, MAX(date) AS latest_post_date
            FROM messages_contents
            GROUP BY thread_id) AS m ON t.id = m.thread_id
WHERE 
t.`creator_uid`='".sInput($_SESSION['uid'])."' 
OR 
t.`receiver_uid`='".sInput($_SESSION['uid'])."' 
GROUP BY t.`id` 
ORDER BY m.latest_post_date DESC") or die (mysql_error());