如何在多个条件下连接表

时间:2014-12-16 10:34:49

标签: sql-server-2008 join

我必须使用join从两个表中选择数据,这两个表都是单独工作但不能一起工作,当我执行完整查询时它不起作用但是当单独执行两个连接时示例:

select 
dbo.mail_Messages.Subject,
dbo.mail_Messages.Body,
dbo.mail_Messages.Date,
dbo.mail_Messages.MessageID
--dbo.mail_Messages.ParrentId
from
dbo.mail_Messages
join
dbo.mail_Reply as mr1
on
mr1.MessageID = dbo.mail_Messages.MessageID

=============================================== =====

select 
dbo.mail_Messages.Subject,
dbo.mail_Messages.Body,
dbo.mail_Messages.Date,
dbo.mail_Messages.MessageID
from
dbo.mail_Messages
join
dbo.mail_Reply as mr2
on
mr2.ParrentId = dbo.mail_Messages.MessageID

以上查询工作正常。

但是当我执行下面的查询(上述查询的组合)时,它什么都不返回。

select 
dbo.mail_Messages.Subject,
dbo.mail_Messages.Body,
dbo.mail_Messages.Date,
dbo.mail_Messages.MessageID
--dbo.mail_Messages.ParrentId
from
dbo.mail_Messages
join
dbo.mail_Reply as mr1
on
mr1.MessageID = dbo.mail_Messages.MessageID
join
dbo.mail_Reply as mr2
on
mr2.ParrentId = dbo.mail_Messages.MessageID

我还附上了一张图片:

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为您需要根据Message Id或ParentID进行过滤并返回消息的状态

SELECT DISTINCT T1.* 
FROM mail_Reply T2
JOIN mail_Messages T1 ON (T2.[MESSAGE ID]=T1.[MESSAGE ID] OR T2.PARENTID=T1.[MESSAGE ID])

现在,如果您想使用Message Id或ParentID进行过滤,请使用以下代码

附加代码
AND (T2.[MESSAGE ID]=2 OR T2.PARENTID=2)

现在,如果您想使用Message Id或ParentID进行过滤,而UserID会使用以下代码附加代码

AND (T2.[MESSAGE ID]=2 OR T2.PARENTID=2) AND T2.USERID=1