【问题标题】:Sort MySQL-Result correctly (Probably need a sub-query)正确排序 MySQL-Result(可能需要子查询)
【发布时间】:2015-09-10 21:56:29
【问题描述】:

我想创建一个消息系统,用户可以在其中互相发送消息。它应该像 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

【问题讨论】:

    标签: mysql sorting subquery sql-order-by


    【解决方案1】:

    您需要加入一个子查询:

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

    【讨论】:

    • 谢谢,它似乎可以正确排序,但它没有显示消息线程的最新文本。我试图在子查询中添加text,但它根本没有显示任何文本。对于已发送的最新文本,我是否需要另一个子查询?
    • 我以为你只是想按最新消息时间订购,而不是显示最新消息。请参阅stackoverflow.com/questions/7745609/… 了解如何获取具有最新日期的整行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多