SELECT s1.receiverID, s2.senderID
FROM messages as s1
LEFT JOIN messages as s2 ON s1.receiverID = s2.senderID
我想组合“messages”表,其中senderID和receiverID是相同的,以实现像会话流一样的东西,但是当我运行它时,它返回总共10,422行。当所有行都是3000时,它如何返回更多?!
//示例场景:id = 8的用户访问此url sample.com/inbox/user=275。我希望显示它们之间的所有消息,以实现对话流/聊天等功能。
答案 0 :(得分:2)
你不想加入。你只想获得所有用户都是发送者和接收者的消息。
select * -- (or whatever)
from messages
where
(senderid = [userId] and receiverid = [otherUserId])
or (senderid = [otherUserId] and receiverid = [userId])
你写的连接是说“给我系统中的每个消息组合,其中一条消息的发送者与另一条消息的接收者相同,如果有人收到了消息但没有发送任何消息,给我看那些带有空值的发送者值。“
答案 1 :(得分:1)
也许这就是你真正想要的东西?
select t1.senderID as t1senderID, t1.receiverID as t1receiverID,
t2.senderID as t2senderID, t2.receiverID as t2receiverID
from messages t1
join messages t2
on t1.senderID = t2.receiverID and t1.receiverID = t2.senderID
样本日期会有很大帮助。
修改强>
鉴于此评论:
我们有用户A和用户B,我想要返回它们之间的所有消息
你正在寻找这个:
select * from t1
where (senderID = 'A' and receiverID = 'B') or
(senderID = 'B' and receiverID = 'A')
答案 2 :(得分:0)
此示例可帮助您找出在连接后获得更多行的原因。
rID sID
1 2
1 3
2 1
3 1
s1.rID s1.sID s2.rID s2.sID
1 2 2 1
1 2 3 1
1 3 2 1
1 3 3 1
2 1 1 2
3 1 1 3