SQL查询:如何进行多次计数?(返回帖子数量以及每个论坛的主题数量)

时间:2009-10-07 10:20:16

标签: sql

我在获取数据库中每个论坛的帖子和主题数量方面遇到了一些麻烦。我可以通过2个查询得到这些值,但我想知道是否可以只用一个查询来完成它。

此查询获取每个论坛的主题数量:

select forums.forumId, forums.forumName, count(*) as Topics FROM Topics 
INNER JOIN forums ON forums.forumId = topics.forumID 
GROUP BY forums.forumId;

此查询获取每个论坛的帖子数量:

select forums.forumId, forums.forumName, count(*) as Posts FROM posts 
INNER JOIN topics ON topics.topicID = posts.topicId 
INNER JOIN forums ON forums.forumId = topics.forumID 
GROUP BY forums.forumId;

如何在一个查询中同时获得帖子和主题数?

2 个答案:

答案 0 :(得分:3)

SELECT  forums.forumId, forums.forumName,
        COUNT(DISTINCT topics.TopicID) AS Topics,
        COUNT(*) as Posts
FROM    forums
INNER JOIN
        topics
ON      topics.forumID = forums.forumId
INNER JOIN
        posts 
ON      posts.topicId  = topics.topicID
GROUP BY
        forums.forumId

答案 1 :(得分:0)

SELECT  forums.forumId, forums.forumName,
        COUNT(DISTINCT topics.TopicID) AS Topics,
        COUNT(posts.topicId) as Posts
FROM    forums
LEFT OUTER JOIN topics
ON      topics.forumID = forums.forumId
LEFT OUTER JOIN posts 
ON      posts.topicId  = topics.topicID
GROUP BY
        forums.forumId

如果您想计算零主题或帖子的论坛

,您想使用左外连接