以下是聊天消息和用户的表格结构。
我希望来自用户的所有对话的最新1条消息,例如用户2
ChatMsgs
========
+--------+-----------+----------+-----------+
| ChatID | FKFromUID | FKToUID | Message |
+--------+-----------+----------+-----------+
| 1 | 3 | 2 | Hello1 |
| 2 | 2 | 1 | Hello2 |
| 3 | 2 | 3 | Hello3 |
| 4 | 3 | 2 | Hi1 |
| 5 | 2 | 3 | Hi2 |
| 6 | 3 | 2 | Hi3 |
+--------+-----------+----------+-----------+
Users
======
+--------+----------+
| UserID | Fullname |
+--------+----------+
| 1 | User1 |
| 2 | User2 |
| 3 | User3 |
+--------+----------+
我想将结果过滤为特定用户,例如用户2
+--------+----------+---------+
| UserID | Fullname | Message |
+--------+----------+---------+
| 3 | User3 | Hi3 |
| 1 | User1 | Hello2 |
+--------+----------+---------+
正如您在结果集中看到的那样,User2的信息/列没有,但是对于其他用户,但只有那些在FKFromUID或FKToUID中存在User2的记录。
这是我创建的查询,但是如果用户退出它,则会提供额外的记录。
select U.UserID
, FullName
, Message
from ChatMsgs C
JOIN
( select max(ChatID) chatID
from ChatMsgs
group
by FKToUID
, FKFromUID
) CC
ON C.ChatID = CC.ChatID
JOIN Users U
ON U.UID = C.FKFromUID
where C.FKToUID = 2
union
select U.UserID, FullName, Message from ChatMsgs C JOIN (select max(ChatID) chatID from ChatMsgs group
by FKToUID, FKFromUID) CC ON C.ChatID=CC.ChatID JOIN Users U ON U.UID=C.FKToUID where C.FKFromUID=2
答案 0 :(得分:0)
如果我理解了您的问题,您只需选择所需的ChatMsgs
(例如FKToUID = 2
)并加入Users
。
SELECT Users.UserID, Users.Fullname, ChatMsgs.Message
FROM ChatMsgs
INNER JOIN Users ON ChatMsgs.FKFromUID = Users.UserID
WHERE ChatMsgs.FKToUID = 2
答案 1 :(得分:0)
对于用户2,您可以获取相关聊天的最大ID和与用户的联接
select User.UserID, Users.Fullname, t.Message
from (
select case when FKFromUID = 2 then FKToUID else FKFromUID
END as UserID
from ChatMsgs
where id in (
select max(id)
from ChatMsgs where FKFromUIDFromUID = 2
union
select max(id)
from ChatMsgs where FKToUID = 2
) ) t
inner join users on t.UserID = Userse .UserID
答案 2 :(得分:0)
我一直认为必须有一种更简单的方法......但这似乎有用。
样本: http://rextester.com/MUMAVP47179
SELECT U.userID, U.FullName, Cm.Message
FROM (SELECT MAX(Z.ChatID) chatID, UID
FROM (SELECT ChatID, case when FKFROMUID = 2 then FKTOUID else FKFROMUID end as UID
FROM ChatMsgs) Z
GROUP BY UID) Y
INNER JOIN Users U
on U.userID = Y.UID
INNER JOIN ChatMsgs CM
on Cm.ChatID = Y.ChatID
ORDER BY Y.chatID desc;
答案 3 :(得分:0)
select U.UserID, FullName, Message, C.CreationTime ChatTime from UserChats C JOIN (select max(UserChatID) chatID from UserChats group by FKToUserID, FKFromUserID) CC ON C.UserChatID=CC.ChatID JOIN Users U ON U.UserID=C.FKFromUserID where C.FKToUserID=@userID
UNION
select U.UserID, FullName, Message, C.CreationTime ChatTime from UserChats C JOIN (select max(UserChatID) chatID from UserChats group by FKFromUserID, FKToUserID) CC ON C.UserChatID=CC.ChatID JOIN Users U ON U.UserID=C.FKToUserID where C.FKFromUserID=@userID