正确排序MySQL-Result(可能需要子查询)

时间:2015-09-10 21:56:30

标签: mysql sorting subquery sql-order-by

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

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

这是我的SELECT - 声明,我想我需要一个子查询,让它按最新的日期和文字排序,但我不熟悉,也不知道在哪里把它和如何?

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

    $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_assigniduidthread_idstatusdate

messages_contentiduidthread_idtextdate

messages_threadidcreator_uidreceiver_uid

1 个答案:

答案 0 :(得分:0)

您需要加入以下的子查询:

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());