0

我试图对对话之类的消息进行分组,user1 是@user(登录用户)用户名,UserFullName 始终是未登录用户(与谁进行对话)消息,日期将是拥有最后一条消息的人

example 1: 
FromUser | ToUser | Message | Date
User2    | User1  | hi      | 01/01/2013 20:00
User1    | User2  | hi back | 01/01/2013 21:00

userfullname and username will be from touser (non logged)
message and date from fromuser (logged in @user, as last message in group)

example 2: 
FromUser | ToUser | Message | Date
User1    | User2  | hi      | 01/01/2013 20:00
User2    | User1  | hi back | 01/01/2013 21:00

userfullname and username will be from fromuser (non logged in)
message and date from fromuser (logged in @user as its the last message in group)

如果你们中的任何人使用过他们的消息系统,这将像 facebook 对话一样显示。谢谢大家!:) 只想着 sql 就炸我的脑袋

SELECT        
CM.FromUser, CM.ToUser, CM.Message, CM.Date, 
U.UserId, U.UserFullName, U.UserName, U.UserPhoto
FROM
ConversationMessages AS CM 
INNER JOIN
Users AS U ON U.UserName = CM.FromUser
WHERE
CM.ToUser = @user
ORDER BY 
CM.Date DESC 
4

1 回答 1

1

答案与您之前的问题类似。但是,现在必须考虑到@user消息中的任何一个用户。

在这种情况下,row_number()没有直接的帮助。

以下是不同之处。现在有一个子查询可以将两个用户按“规范”顺序排列。因此,它们之间的所有消息都具有相同的User1User2(基于字母顺序)。

partition by子句使用这些列,因此所有消息都包含在seqnum计算中。该Users表现在直接获取有关当前用户的信息。

select FromUser, ToUser, Message, [Date], UserId, UserFullName, UserName, UserPhoto
from (SELECT CM.FromUser, CM.ToUser, CM.Message, CM.[Date], U.UserId,
             U.UserFullName, U.UserName, U.UserPhoto,
             row_number() over (partition by CM.User1, CM.User2
                                order by CM.[Date] desc) as seqnum
      FROM (select CM.*,
                   (case when FromUser < ToUser then FromUser else ToUser end) as User1,
                   (case when FromUser < ToUser then ToUser else FromUser end) as User2
            from ConversationMessages CM
           ) CM CROSS JOIN
           (select *
            from Users U
            where @user = u.UserName
           ) U
      WHERE @user in (CM.ToUser, CM.FromUser)
     ) s
WHERE seqnum = 1
ORDER BY s.[Date] DESC ;

编辑:

以上返回 的用户信息@user。对于其他参与者:

select FromUser, ToUser, Message, [Date], UserId, UserFullName, UserName, UserPhoto
from (SELECT CM.FromUser, CM.ToUser, CM.Message, CM.[Date], U.UserId,
             U.UserFullName, U.UserName, U.UserPhoto,
             row_number() over (partition by CM.User1, CM.User2
                                order by CM.[Date] desc) as seqnum
      FROM (select CM.*,
                   (case when FromUser < ToUser then FromUser else ToUser end) as User1,
                   (case when FromUser < ToUser then ToUser else FromUser end) as User2
            from ConversationMessages CM
           ) CM JOIN
           Users U
           on U.UserName <> @user and
              U.UserName in (CM.FromUser, CM.ToUser)
      WHERE @user in (CM.ToUser, CM.FromUser)
     ) s
WHERE seqnum = 1
ORDER BY s.[Date] DESC ;
于 2013-09-11T22:15:57.543 回答