我想在列中获得最新的行,但我需要在将它们彼此分组之前获取它们。如果我把order by by group by,mysql命令将它们分组之前。
我尝试做什么,为用户的最后一条消息分组消息(比如Facebook聊天。)
如果客户有3个对话,他/她需要将消息列表视为最后一个对话框:
(假设移动用户的昵称是Rob,他正在列出他的消息历史......)
Rob - >托马斯(你好,我会尽快回来。)
Dyne - >罗布(你在哪里?)
Rob - >丹尼拉(你好吗?)
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
答案 0 :(得分: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
答案 1 :(得分:0)
我使用子查询解决了我的问题,并使用以下SQL语句分组:
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);