表在sql server 2008中没有正确连接

时间:2014-12-31 07:21:05

标签: sql sql-server-2008 select join

我必须显示dbo.mail_Messages表的结果,但问题是应显示Messages哪些ID不在dbo.mail_Reply中。为此,我使用下面的查询,但它没有显示任何内容。

我还附了一个屏幕截图:

enter image description here

我该如何解决这个问题?

我的代码:

SELECT
    dbo.mail_Messages.MessageID,
    dbo.mail_Users_Messages_Mapped.PlaceHolderID,
    IsRead,
    SenderId,
    dbo.mail_Messages.Subject,
    dbo.mail_Messages.Body,
    dbo.mail_Messages.Date,UserEmail
FROM
    dbo.mail_Users_Messages_Mapped
JOIN
   dbo.mail_Messages ON dbo.mail_Messages.MessageID = dbo.mail_Users_Messages_Mapped.MessageID
JOIN
   dbo.mail_Users ON dbo.mail_Users.UserID = dbo.mail_Users_Messages_Mapped.UserId
JOIN
   dbo.mail_Reply ON dbo.mail_Reply.MessageID = dbo.mail_Messages.MessageID
WHERE
   UserEmail = 'user1'
   AND dbo.mail_Users_Messages_Mapped.PlaceHolderId = 1
   AND dbo.mail_Messages.MessageID != dbo.mail_Reply.MessageID

1 个答案:

答案 0 :(得分:1)

您的查询将产生一个空结果,因为它有两个矛盾的条件。在join子句中,您要求:

dbo.mail_Reply.MessageID = dbo.mail_Messages.MessageID

where条款中,您要求

dbo.mail_Messages.MessageID != dbo.mail_Reply.MessageID

由于某个值不能相等且不等于另一个值,因此这两个条件的组合为空结果。

解决此问题的一种方法是,如果我理解正确的要求,就是停止join mail_Reply,并改为使用in运算符:

SELECT
dbo.mail_Messages.MessageID,
dbo.mail_Users_Messages_Mapped.PlaceHolderID,
IsRead,
SenderId,
dbo.mail_Messages.Subject,
dbo.mail_Messages.Body,
dbo.mail_Messages.Date,UserEmail
FROM
dbo.mail_Users_Messages_Mapped
join
dbo.mail_Messages on dbo.mail_Messages.MessageID = dbo.mail_Users_Messages_Mapped.MessageID
join
dbo.mail_Users on dbo.mail_Users.UserID = dbo.mail_Users_Messages_Mapped.UserId
where
UserEmail = 'user1'
and
dbo.mail_Users_Messages_Mapped.PlaceHolderId = 1
and
dbo.mail_Messages.MessageID NOT IN (SELECT MessageID FROM dbo.mail_Reply)