SQL-无法显示包含0的计数值

时间:2015-01-28 17:22:45

标签: mysql sql sql-server inner-join query-builder

有2个表讨论和评论, 讨论表有D1和D2 注释表有(C1,D2),(C2,D2)

SELECT        Discussion.DiscussionID, COUNT(Comment.CommentID) AS Expr1
FROM            Comment INNER JOIN
                     Discussion ON Comment.DiscussionID = Discussion.DiscussionID INNER JOIN
                     Category ON Discussion.CategoryID = Category.CategoryID
GROUP BY Discussion.DiscussionID

我想要这样的输出......

Dicussion ID||   Comment COunt
D1                  0
D2                  2

但结果如此

Dicussion ID||   Comment COunt
D2                  2

2 个答案:

答案 0 :(得分:4)

Inner Join转换为Right Join,以便从Discussion表中获取所有行。

SELECT Discussion.DiscussionID,
       Count(Comment.CommentID) AS Expr1
FROM   Comment
       RIGHT JOIN Discussion
               ON Comment.DiscussionID = Discussion.DiscussionID
       INNER JOIN Category
               ON Discussion.CategoryID = Category.CategoryID
GROUP  BY Discussion.DiscussionID 

答案 1 :(得分:1)

或使用左连接

SELECT Discussion.DiscussionID,
       Count(Comment.CommentID) AS Expr1
FROM   Discussion
       INNER JOIN Category
               ON Discussion.CategoryID = Category.CategoryID
       LEFT JOIN Comment
               ON Comment.DiscussionID = Discussion.DiscussionID
GROUP  BY Discussion.DiscussionID