1

我有这张桌子:

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'

谢谢!

4

1 回答 1

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
于 2013-11-08T19:03:54.997 回答