SQL Server离开了条件,没有给我我想要的结果

时间:2011-06-09 19:59:41

标签: sql-server left-join

先查询,然后提问:

SELECT  DISTINCT p.postID, p.postGUID, p.postTitle, p.postTypeID, p.sequence, m.firstname, m.lastname, pt.postTypeName, mc.acceptRejectDate
FROM    post p
INNER JOIN member m ON p.memberGUID = m.memberGUID
INNER JOIN postType pt ON p.postTypeID = pt.postTypeID
LEFT JOIN masterClass mc ON (p.postGUID = mc.postGUID AND mc.isMemberPrivate = 0 AND mc.status = 2 AND mc.acceptRejectDate IS NOT NULL)
WHERE   p.postTitle LIKE '%five%'
AND p.isActive = 1
ORDER BY    p.postTypeID, p.sequence, mc.acceptRejectDate

我在这里要做的是从“posts”表中获取所有结果,其中isActive = 1且标题包含“five”。很容易。

某些结果也与masterClass表有关联。对于那些结果,如果isMemberPrivate为零,状态为2,并且有一个acceptRejectDate,我只想包含它们。

我认为这很容易,但是当我运行查询时,我得到的结果包括一些不符合主类加入条件的帖子。并且,有一些结果显示为具有空值,但在我查看原始数据时显然不会。

此查询中是否有任何内容出错并导致我的结果不正确?

2 个答案:

答案 0 :(得分:4)

通过阅读您的问题,我相信您希望包含所有在masterClass表中没有记录的结果,或者在masterClass表中包含符合条件的记录。如果将条件向下移动到WHERE部分,并添加对masterClass表中与任何内容不匹配的记录的检查,则应该得到所需的值。

SELECT  DISTINCT p.postID, p.postGUID, p.postTitle, p.postTypeID, p.sequence, m.firstname, m.lastname, pt.postTypeName, mc.acceptRejectDate
FROM    post p
INNER JOIN member m ON p.memberGUID = m.memberGUID
INNER JOIN postType pt ON p.postTypeID = pt.postTypeID
LEFT JOIN masterClass mc ON p.postGUID = mc.postGUID
WHERE   p.postTitle LIKE '%five%'
AND p.isActive = 1
AND ( mc.postGUID is NULL OR 
     (mc.isMemberPrivate = 0 AND mc.status = 2 AND mc.acceptRejectDate IS NOT NULL)
    )
ORDER BY    p.postTypeID, p.sequence, mc.acceptRejectDate

修改:更改字段,查找从mc.acceptRejectDatemc.postGUID

的NULL

答案 1 :(得分:0)

尝试此操作以明确区分JOIN和过滤条件

...
LEFT JOIN
(
SELECT postGUID, acceptRejectDate
FROM masterClass
WHERE isMemberPrivate = 0 AND status = 2 AND acceptRejectDate IS NOT NULL
) mc ON p.postGUID = mc.postGUID
...