来自多个连接表的COUNT行 - MSSQL

时间:2014-03-04 18:23:22

标签: asp.net sql sql-server count left-join

我正在努力为学校项目建立一个简单的论坛。 我的查询遇到了一些麻烦。 我有3张桌子,我正在尝试加入。 “类别”,“主题”和“发布”。

ERD

ERD

表格数据

分类

Category

线程

Threads

帖子

Posts

(尽管DB中的名称拼写略有不同,但列和表是相同的,如图所示。) 一旦我加入第二个表(“帖子”),“线程” - 计数的结果就错了。 如果我只离开连接并计算“线程”中的行,那么结果是正确的。

当我这样做时:

    SELECT Category.Name AS CategoryName, Category.Description AS
    CategoryDescription, COUNT(Threads.Id) AS NumberOfThreads
    FROM Category
    LEFT JOIN Threads ON Threads.FkCategoryId = Category.Id GROUP
    BY Category.Name, Category.Description

结果

enter image description here

返回“线程”中的实际行数。到目前为止一切都很好, 但是当我添加第二个连接时

    SELECT Category.Name AS CategoryName, Category.Description AS CategoryDescription,
    COUNT(Threads.Id) AS NumberOfThreads,
    COUNT(Posts.Id) AS NumberOfPosts
    FROM Category
    LEFT JOIN Threads ON Threads.FkCategoryId = Category.Id
    LEFT JOIN Posts ON Posts.FkThreadId = Threads.Id
    GROUP BY Category.Name, Category.Description

然后我得到了这个结果:

enter image description here

其中“帖子”中的实际行数显示为“主题”和“帖子”。

我还尝试将多个查询组合在一起,如下所示:

    SELECT Category.Name AS CategoryName, Category.[Description] AS
    CategoryDescription, COUNT(Threads.Id) AS NumberOfThreads
    FROM Category
    LEFT JOIN Threads ON Category.Id = Threads.FkCategoryId
    GROUP BY Category.Name, Category.Description;

    SELECT COUNT(Posts.Id) AS NumberOfPosts
    FROM Category
    LEFT JOIN Threads ON Category.Id = Threads.FkCategoryId
    LEFT JOIN Posts ON Threads.Id = Posts.FkThreadId
    GROUP BY Category.Id;

这给了我这个结果:

enter image description here

这是正确的数据。我只想在1个查询中组合它,因为我不能“Eval”“NumberOfPosts”形成第二个查询。

我收到此错误:

  

“DataBinding:'System.Data.DataRowView'不包含属性   名称为'NumberOfPosts'“

我已经阅读并尝试了很多不同的东西,并且不知道如何解决它。我希望有人可以提供帮助。

2 个答案:

答案 0 :(得分:2)

我认为您在第二次加入时错过了加入条件Post.FkUserId = Threads.FkUserId

尝试:

 LEFT JOIN Posts ON Threads.Id = Posts.FkThreadId  AND PostFkUserId = Threads.FkUserId

基本上,您查询会匹配更多记录,因为您只能加入Threads.Id = Posts.FkThreadId。在帖子表中有7条记录,其中FkThreadId为7,6,6,5,2,2,2。

答案 1 :(得分:0)

请尝试以下内容:

SELECT CatThread.CategoryName, CatThread.CategoryDescription,
    CatThread.NumberOfThreads,
    COUNT(Posts.Id) AS NumberOfPosts
FROM 
   ( select Category.Id, Category.Name AS CategoryName, Category.Description AS CategoryDescription,
    COUNT(Threads.Id) AS NumberOfThreads
    from Category
      LEFT JOIN Threads ON Threads.FkCategoryId = Category.Id
    group by  Category.Id, Category.Name, Category.Description) CatThread
    LEFT JOIN Threads ON Threads.FkCategoryId = CatThread.Id
    LEFT JOIN Posts ON Posts.FkThreadId = Threads.Id
GROUP BY CatThread.CategoryName, CatThread.CategoryDescription,
    CatThread.NumberOfThreads

我没有创建表格,以确保它有效,但我相信这个查询应该能给你你想要的东西。您可能需要调整语法等。基本思想是使用子查询在单行中获取每个类别的线程数,然后可以将其连接到帖子表。