我有这张桌子:
fromJID | toJID | sentDate | body
我需要用户(toJID)的最后五个对话的最后一条消息
我试试这个,但这会返回第一个会话消息,而不是最后一个消息。
SELECT
body as mensagem,
fromJID,
toJID,
sentDate
FROM ofmessagearchive
WHERE toJID = '1945'
GROUP BY fromJID
ORDER BY sentDate DESC
LIMIT 0, 5
数据示例:
fromJID| toJID | sentDate | body (message)
'1945' | '2042' | 1383934233976 | '1\n'
'1945' | '2042' | 1383934234429 | '2\n'
'1945' | '2042' | 1383934234430 | '3\n'
'2042' | '1945' | 1383934237053 | '1\n'
'2042' | '1945' | 1383934237374 | '2\n3'
'2042' | '1945' | 1383934237523 | '\n'
'2042' | '1945' | 1383934242018 | '3\n'
'1945' | '1946' | 1383934364814 | '1\n'
'1945' | '1946' | 1383934365118 | '2\n'
'1945' | '1946' | 1383934365366 | '3\n'
'1946' | '1945' | 1383934367271 | '1\n'
'1946' | '1945' | 1383934367517 | '2\n'
'1946' | '1945' | 1383934367782 | '3\n'
谢谢!
答案 0 :(得分:3)
尝试这一点,使用子查询获取每个对话的最后一个帖子并将其连接到主表: -
SELECT a.body as mensagem,
a.fromJID,
a.toJID,
a.sentDate
FROM ofmessagearchive a
INNER JOIN
(
SELECT fromJID, toJID, MAX(sentDate) AS MaxSentDate
FROM ofmessagearchive
GROUP BY fromJID, toJID
) b
ON a.fromJID = b.fromJID
AND a.toJID = b.toJID
AND a.sentDate = b.MaxSentDate
WHERE ta.oJID = '1945'
ORDER BY a.sentDate DESC
LIMIT 5