如何获取用户之间对话的最新消息? (聊天系统)

时间:2015-12-30 23:49:16

标签: php mysql

我正在构建一个私人消息系统。

我希望按照通话时间获取最新消息。现在它按时间顺序显示消息,但我想以反向时间顺序排列,最新消息在顶部等等。

SELECT `messages`.`id`,
    `messages`.`sender`,
    `messages`.`receiver`,
    `messages`.`message`,
    `messages`.`datetime`,
    `messages`.`classifield_id`
FROM `augl`.`messages`;

功能

public function getMessageList()
{
    $current_user = $this->accounts->getUserId();

    $query = $this->db->query("SELECT * FROM(
                                SELECT id, LEAST(receiver) as receiver, LEAST(sender) AS sender, message, datetime, classifield_id 
        FROM messages
        WHERE sender='$current_user' OR receiver = '$current_user' 
        Group By (if(sender > receiver,  sender, receiver))
               , (if(sender > receiver,  receiver, sender))
        ) 
            as id");

    $result =  $query->result();

    //var_dump($result); die;

    foreach ($result as $messages )
    {
        $return[$messages->id] = $messages;

        if ($messages->receiver === $current_user)
        {
            $return[$messages->id]->userr = $this->accounts->getUsername($messages->sender);
            $return[$messages->id]->userid = $messages->sender;
            //$return[$messages->id]->message = $messages->message;

        }
        else
        {
            $return[$messages->id]->userr = $this->accounts->getUsername($messages->receiver);
            $return[$messages->id]->userid = $messages->receiver;
            //$return[$messages->id]->message = $messages->message;
        }


    }

    return $return;
}

2 个答案:

答案 0 :(得分:0)

看起来如果你将“LEAST”更改为“GREATEST”可能会修复它。

答案 1 :(得分:0)

请参阅MySQL手册中的教程。你想要GROUPWISE MAXIMUM显然是MIN而不是MAX。