我有一个简单的消息传递模式,其中每条消息都有一个senderFK和一个recipientFK,每个消息映射到一个用户记录。对于当前用户,我需要获得所有不同的线程。对于已发送或接收消息的用户,不同的线程是senderFK或recipientFK。
所以,例如:
此查询获取向当前用户发送消息的所有用户:
SELECT DISTINCT senderFK AS threadID FROM Messages
WHERE recipientFK = 'usr_developer'
此查询获取从当前用户收到消息的所有用户:
SELECT DISTINCT recipientFK AS threadID FROM Messages
WHERE senderFK = 'usr_developer'
如何将这些查询组合到一个表中,该表为每个用户和一个列(threadID)分别设置了一个行?
答案 0 :(得分:3)
这样的事情应该有效:
SELECT recipientFK as UserId, senderFK as ThreadID
FROM Messages
UNION
SELECT senderFK as UserID, recipientFK AS threadID
FROM Messages
此方法会根据您的评论...a distinct row for each user ...
答案 1 :(得分:2)
SELECT senderFK AS threadID
FROM Messages
WHERE recipientFK = 'usr_developer'
UNION
SELECT recipientFK AS threadID
FROM Messages
WHERE senderFK = 'usr_developer'
请注意,您不再需要DISTINCT
,因为UNION
会过滤掉任何重复项。
答案 2 :(得分:1)
如果是SQL Server,您可以执行以下操作:
select distinct case when senderFK = 'usr_developer' then recipientFK else senderFK end ThreadID
from Messages
where 'usr_developer' in (senderFK, recipientFK)
同样,如果您愿意/它优于:
,您可以更改WHERE子句select distinct case when senderFK = 'usr_developer' then recipientFK else senderFK end ThreadID
from Messages
where senderFK = 'usr_developer'
or recipientFK = 'usr_developer'