inner Join不返回所有行

时间:2012-03-26 00:47:08

标签: sql

我正在使用C#Webforms构建一个博客引擎,我有以下代码可以选择所有当前的博客帖子,这意味着它们应该被显示,并且每个博客文章的所有评论的数量都会很好。

SELECT PostID, PostTitle, PostDate, PostTeaser, Count(CommentID) AS CountOfCommentID, PostCurrent 
FROM TBLBlogPost 
    INNER JOIN TBLBlogComment ON PostID = PostCommentFK 
GROUP BY PostID, PostTitle, PostDate, PostTeaser, PostCurrent
HAVING PostCurrent = 'True'

问题是它只选择至少有一条评论的博文。

有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

然后你应该使用LEFT JOIN,而不是INNER JOIN

SELECT PostID, PostTitle, PostDate, PostTeaser, Count(CommentID) AS CountOfCommentID, PostCurrent 
FROM TBLBlogPost 
    LEFT JOIN TBLBlogComment ON PostID = PostCommentFK 
GROUP BY PostID, PostTitle, PostDate, PostTeaser, PostCurrent
HAVING PostCurrent = 'True'

INNER JOIN表示匹配表必须匹配,否则它不会填充结果集。 LEFT JOIN表示如果未进行匹配,则会使用NULL

填充该表中的所有内容

Here是不同SQL连接的良好直观表示。

相关问题