0

我想在列中获取最新的行,但我需要在将它们分组之前获取它们。如果我在 group by 之后放置 Order by,则 mysql 对它们之前分组的排序。

我试图做的,为用户的最后一条消息分组消息(比如facebook聊天。)

如果客户有 3 个对话,他/她需要将消息列表视为最后一个对话:

(假设,移动用户昵称是 Rob,他正在列出他的消息历史......)

Rob -> Thomas(你好,我会尽快回来。)

Dyne -> Rob(你在哪里?)

Rob -> Danilla(你好吗?)

SELECT 
    u.userNickName, 
    u.userFBID, 
    m.didRead, 
    max(m.messageID) messageID, 
    m.messageContent, 
    m.srcUserID, 
    m.destUserID, 
    m.messageSendDate
FROM 
users u, messages m
WHERE
(m.srcUserID='122' || m.destUserID ='122')
AND
u.userID =  m.destUserID
GROUP BY
u.userNickName
4

2 回答 2

0

I solved my question with using subquery and group by with following SQL Statement :

SELECT 
    u.userNickName,
    u.userFBID,
    m.didRead,
    m.messageID,
    m.messageContent,
    m.srcUserID,
    m.destUserID,
    m.messageSendDate 
FROM 
    users u, 
    messages m 
WHERE 
    (u.userID = m.srcUserID or u.userID = m.destUserID) 
AND 
CASE 
    WHEN m.srcUserID='122' THEN u.userID= m.destUserID
    WHEN m.destUserID ='122' THEN u.userID= m.srcUserID
    ELSE -1
END 
AND 
m.messageID in (select max(m.messageID) from users u, messages m where (u.userID = m.srcUserID or u.userID = m.destUserID) group by u.userNickName);
于 2013-09-12T15:02:22.513 回答
0

您正在寻找的不是group但是LIMIT- 您可以根据日期以 desc 顺序对结果进行排序,并将结果集限制为包含最后 3 条消息:

SELECT 
    u.userNickName, 
    u.userFBID, 
    m.didRead, 
    max(m.messageID) messageID, 
    m.messageContent, 
    m.srcUserID, 
    m.destUserID, 
    m.messageSendDate
FROM 
users u, messages m
WHERE
(m.srcUserID='122' || m.destUserID ='122')
AND
u.userID =  m.destUserID
ORDER BY m.messageSendDate DESC
LIMIT 3
于 2013-09-10T14:57:06.490 回答