如何进行对话'邮件系统中的最后一条消息 即。主页(whatsapp)
我已创建此存储过程但无法获得正确的结果。
SELECT
Max(msg.msgThread) as msgThread,
Max(msg.msgId) AS msgId,
Max(msg.msgDate) AS msgDate,
min(DATEDIFF(MINUTE,msgCreatedDate,GETUTCDATE())) AS mintuesago,
msgReceiverId,
msgSenderId,
max (msgmsg) as msg, --I am getting alpabatic max msg instead last msg.
usr.umName,
usr.umProfilePic
FROM messages AS msg
Inner Join usermaster AS usr ON ((msg.msgSenderId = usr.umId)
or (msg.msgReceiverId = usr.umId) )
WHERE
--usr.umId=msg.msgReceiverId
usr.umId!=3198
and (msg.msgSenderId=3198 or msg.msgReceiverId =3198)
GROUP BY usr.umName, usr.umProfilePic, msgReceiverId, msgSenderId, msgmsg
--,msgSentById
ORDER BY max(DATEDIFF(MINUTE,msgDate,GETUTCDATE()))
有了这个,我可以得到用户列表, 但是当两个用户都相互发送消息时,它会给出两行,其中包含两个用户的最后一条消息。
答案 0 :(得分:1)
虽然很难在没有任何数据的情况下进行故障排除并且不得不推断您的表结构,但看起来将msgThread添加到您的分组中会阻止来自同一消息线程的重复记录。选择前1将确保您只获得最新记录(假设您的order by子句正常工作)。
供将来参考:如果您提供样本数据,解释您所获得的内容,并解释您想要获得的内容,那么帮助您将会容易得多。
未经测试的代码:
SELECT top 1
msg.msgThread as msgThread,
Max(msg.msgId) AS msgId,
Max(msg.msgDate) AS msgDate,
min(DATEDIFF(MINUTE,msgCreatedDate,GETUTCDATE())) AS mintuesago,
msgReceiverId,
msgSenderId,
max (msgmsg) as msg, --I am getting alpabatic max msg instead last msg.
usr.umName,
usr.umProfilePic
FROM messages AS msg
Inner Join usermaster AS usr ON ((msg.msgSenderId = usr.umId)
or (msg.msgReceiverId = usr.umId) )
WHERE
--usr.umId=msg.msgReceiverId
usr.umId!=3198
and (msg.msgSenderId=3198 or msg.msgReceiverId =3198)
GROUP BY msgThread, usr.umName, usr.umProfilePic, msgReceiverId, msgSenderId, msgmsg
--,msgSentById
ORDER BY max(DATEDIFF(MINUTE,msgDate,GETUTCDATE()))