SQL - 上次对话消息列表

SQL - Last conversation Message list

如何在消息系统中获取对话的最后一条消息? IE。 (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()))

有了这个,我可以得到用户列表, 但是当两个用户都互相发送消息时,它会给出两行,其中包含两个用户的最后一条消息。

虽然在没有任何数据并被迫推断您的 table 结构的情况下很难排除故障,但看起来将 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()))