0

我有一张桌子chat
列是"id", "sender", "message", "time", "sender_email"。插入的一些聊天记录chat如下:

1 John hihi 10:45 john@email.com
2 John hihi 10:46 john@email.com
3 Peter hihi 10:47 peter@email.com
4 John hihi 10:48 john@email.com
5 John hihi 10:49 john@email.com
6 John hihi 10:50 john@email.com
7 Mary hihi 10:51 mary@email.com
8 John hihi 10:52 john@email.com
9 Peter hihi 10:53 peter@email.com
10 John hihi 10:54 john@email.com

我想从出现在表格中的人那里收到最后一条消息。
如果有一个人多次出现在表格中,则只需获取他的最后一条消息。
所以我想得到的结果应该是:

10 John hihi 10:54 john@email.com
9 Peter hihi 10:53 peter@email.com
7 Mary hihi 10:51 mary@email.com

有可能这样做吗?
到目前为止,我只是写了一个sql:

SELECT DISTINCT name from chat ORDER BY id DESC

但似乎它无法显示我想要的。

4

2 回答 2

4

您必须确定哪些消息是每个用户的最后一条消息(我正在这样做,timeid如果您知道更高的值肯定等于稍后的消息,您也可以这样做),然后获取该消息的数据:

SELECT chat.*
FROM chat
INNER JOIN
(
    SELECT MAX(time) AS time, sender
    FROM chat
    GROUP BY sender
) lastMsg ON chat.time = lastMsg.time AND chat.sender = lastMsg.sender

这也假设 没有关系time。如果这是可能的,你将不得不通过 id 代替:

SELECT chat.*
FROM chat
INNER JOIN
(
    SELECT MAX(id) AS id
    FROM chat
    GROUP BY sender
) lastMsg ON chat.id = lastMsg.id
于 2012-09-10T04:53:19.507 回答
0
SELECT id, sender, message, time, sender_email FROM
    (SELECT * FROM chat ORDER BY time DESC) AS temp 
GROUP BY sender ORDER BY id DESC
于 2012-09-10T05:43:08.960 回答