我有三张桌子 - 章节,主题和评论。
简单视图:
-SectionId
-ThemeId -SectionId
-CommentId -ThemeId
我需要编写sql查询来获得如下结果:
-SectionId -CountOfThemes -CountOfComments
Select
Section.SectionId As SessionId,
Section.SectionTitle As SessionTitle,
Count(Distinct Theme.ThemeId) As CountTheme,
Count(Distinct Comment.CommentId) As CountComment
From Section
Left Join Theme On Section.SectionId = Theme.SectionId
LEFT JOIN Comment ON Theme.ThemeId = Comment.ThemeId
Group By
Section.SectionId,
Section.SectionTitle
答案 0 :(得分:1)
尝试使用COUNT(DISTINCT Theme.ThemeId)和COUNT(DISTINCT Comment.CommentId)
我认为您的问题是主题和评论之间存在一对多的关系,因此您会在有多个评论的地方获得重复的ThemeIds。
您的代码:left Join Comment On Comment.ThemeId = Theme.ThemeId
我会考虑更改为LEFT JOIN Comment ON Theme.ThemeId = Comment.ThemeId