如何修复右外连接

时间:2019-02-21 07:55:11

标签: sql sql-server join left-join outer-join

我正在尝试使外部连接使用下面的代码; 使用(左外,右外,全外和内联接)的结果是相同的结果。 我正在尝试返回所有出版商名称,包括尚未与任何图书关联的出版商!

SELECT P.PublisherName,
    COUNT(B.BookID) AS BookPublished
    FROM LR_Publisher AS P LEFT OUTER JOIN LR_Book As B 
    ON P.PublisherID = B.PublisherID
    WHERE (P.PublisherID = @pPublisherID OR @pPublisherID IS NULL)
    GROUP BY PublisherName

预先感谢

3 个答案:

答案 0 :(得分:1)

没有出版任何书籍的出版商会被GROUP BY过滤掉。 可以使用GROUP BY ALL来解决:

SELECT P.PublisherName,
COUNT(B.BookID) AS BookPublished
FROM LR_Publisher AS P 
LEFT OUTER JOIN LR_Book As B    ON P.PublisherID = B.PublisherID
-- WHERE (P.PublisherID = @pPublisherID OR @pPublisherID IS NULL)
GROUP BY PublisherName

答案 1 :(得分:1)

你可以这样写

select P.PublisherName,
       isnull(bi.BookPublished, 0) as BookPublished
from LR_Publisher as P
    left join (
        select B.PublisherID, Count(B.BookID) BookPublished
        from LR_Book as B 
        where (@pPublisherID is null or B.PublisherID = @pPublisherID)
        group by B.PublisherID
    ) bi on P.PublisherID = Bi.PublisherID
where (@pPublisherID is null or P.PublisherID = @pPublisherID)

我也不知道group by进行的过滤。谢谢你的提问。

答案 2 :(得分:0)

简单的左联接将帮助您获取所有出版商的名称,包括尚未出版任何书籍的人

   SELECT P.PublisherName 
    FROM LR_Publisher AS P LEFT OUTER JOIN LR_Book As B 
    ON P.PublisherID = B.PublisherID