mysql在对话中获取最后一条消息

时间:2014-03-05 10:22:49

标签: php mysql sql

我目前正在创建私人邮件的收件箱,并希望显示每个唯一身份用户之间发送或接收的最后一条消息。我目前有这个

SELECT
 Message.id, Message.from, Message.body, Message.isread, Message.timestamp,
 User.id, User.username,
FROM messages as Message 
 LEFT JOIN users as User ON (Message.from = User.id)
    WHERE Message.id IN
     (SELECT MAX(`id`) FROM `messages` 
        WHERE `to` = '.$this->currentUser["id"].'
         OR `from` = '.$this->currentUser["id"].'
    GROUP BY `from`,`to`)
 ORDER BY Message.id DESC;

但是它获得了最后发送和收到的消息,我只想要 最后一条消息,该消息是在当前用户和任何其他用户以及该对话所在的用户之间发送的。

 `Message`.`id` is auto incremented, indvidual message id.
 `Message`.`from` is the ID of the user the message is from.
 `Message`.`to` is the ID of the user the message us to.

由于

5 个答案:

答案 0 :(得分:0)

要查找当前用户的最新已发送消息,请

更改:

WHERE `to` = '.$this->currentUser["id"].'
OR `from` = '.$this->currentUser["id"].'

致:

WHERE `from` = '.$this->currentUser["id"].'

要查找任何最新发送或接收的消息,请

更改:

WHERE Message.id IN
 (SELECT MAX(`id`) FROM `messages` 
    WHERE `to` = '.$this->currentUser["id"].'
     OR `from` = '.$this->currentUser["id"].'
GROUP BY `from`,`to`)

致:

WHERE Message.id =
 (SELECT MAX(`id`) FROM `messages` 
    WHERE `to` = '.$this->currentUser["id"].'
     OR `from` = '.$this->currentUser["id"].'
  GROUP BY `from`,`to` ORDER BY 1 DESC LIMIT 1)

要查找任何用户的最新已发送消息,

更改:

WHERE Message.id IN
  (SELECT MAX(`id`) FROM `messages` 
     WHERE `to` = '.$this->currentUser["id"].'
      OR `from` = '.$this->currentUser["id"].'
   GROUP BY `from`,`to`)

致:

WHERE Message.id IN
  (SELECT MAX(`id`) FROM `messages` 
   GROUP BY `from`,`to`)

答案 1 :(得分:0)

这样的简单吗?

SELECT Message.id, Message.from, Message.body, Message.isread, Message.timestamp, User.id, User.username,
FROM messages as Message 
 LEFT JOIN users as User ON (Message.from = User.id)
ORDER BY Message.timestamp DESC
Limit 0, 1;

答案 2 :(得分:0)

它实际上更简单。如果您正在使用有用的时间戳 - 格式(其中最高的墨水编号是最后一个,如UNIX-Time之后的毫秒数或YYYY-MM-DD格式),您可以这样做:

mysql_query("SELECT
 M.id, M.from, M.body, M.isread, M.timestamp,
 U.id, U.username,
FROM messages M 
LEFT JOIN users U ON (M.from = U.id)
WHERE `to` = $this->currentUser["id"]
 OR `from` = $this->currentUser["id"]
ORDER BY M.timestamp DESC
LIMIT 0 , 1");

答案 3 :(得分:0)

明白我的回答可能会来得太晚,但仍然如此。这解决了我的问题:

SELECT id, user_to, user_from, body, msg_time FROM chat
WHERE id IN (SELECT MAX(id) FROM chat WHERE user_to=:id OR user_from=:id GROUP BY user_to,user_from) ORDER BY msg_time DESC

:id后来改为$ id var,如果你使用PDO -

        $stmt=$this->conn->prepare("SELECT id, user_to, user_from, body, msg_time FROM chat
            WHERE id IN (SELECT MAX(id) FROM chat WHERE user_to=:id OR user_from=:id GROUP BY user_to,user_from) ORDER BY msg_time DESC");
        $stmt->execute(array(":id"=>$id));
        $stmt=$stmt->fetchAll(PDO::FETCH_ASSOC);
        return $stmt;

希望这有助于那些仍在寻找的人 - 我花了很长时间;)干杯。

答案 4 :(得分:0)

尝试

SELECT m1.* FROM messages m1 LEFT JOIN messages m2 ON (m1.from = m2.from AND m1.id < m2.id) WHERE m2.id IS NULL;