从主表中选择记录和在另一个表中的每一行的计数

时间:2015-01-07 13:02:40

标签: sql sql-server

我的数据库中有2个表,表与外键有关系 我想从主表中选择所有记录,然后选择另一个表中每行的计数,而不是主表中的相同ID我尝试创建一个选择查询,但它无法正常工作 此查询返回主表中的所有记录+下一个表中所有记录的计数(不是关系中每一行的计数)

    SELECT tblForumSubGroups_1.id, tblForumSubGroups_1.GroupID,
    tblForumSubGroups_1.SubGroupTitle, tblForumSubGroups_1.SubGroupDesc,
    (SELECT COUNT(dbo.tblForumPosts.id) AS Expr1
    FROM dbo.tblForumSubGroups INNER JOIN dbo.tblForumPosts ON 
    dbo.tblForumSubGroups.id = dbo.tblForumPosts.SubGroupID) AS Expr1
    FROM dbo.tblForumSubGroups AS tblForumSubGroups_1 INNER JOIN
    dbo.tblForumPosts AS tblForumPosts_1 ON tblForumSubGroups_1.id 
    = tblForumPosts_1.SubGroupID

4 个答案:

答案 0 :(得分:2)

SELECT  tblForumSubGroups_1.id, tblForumSubGroups_1.GroupID, tblForumSubGroups_1.SubGroupTitle, tblForumSubGroups_1.SubGroupDesc,
        COUNT(tblForumPosts_1.id) AS Expr1
FROM    dbo.tblForumSubGroups AS tblForumSubGroups_1
INNER JOIN  dbo.tblForumPosts AS tblForumPosts_1 ON tblForumSubGroups_1.id = tblForumPosts_1.SubGroupID
GROUP BY tblForumSubGroups_1.id, tblForumSubGroups_1.GroupID, tblForumSubGroups_1.SubGroupTitle, tblForumSubGroups_1.SubGroupDesc

答案 1 :(得分:0)

不要混合子查询和连接逻辑。只使用其中一个。我更喜欢子选择。

SELECT tblForumSubGroups_1.id,
       tblForumSubGroups_1.GroupID,
       tblForumSubGroups_1.SubGroupTitle,
       tblForumSubGroups_1.SubGroupDesc,
       (SELECT COUNT(*)
        FROM dbo.tblForumPosts
        WHERE dbo.tblForumSubGroups.id = dbo.tblForumPosts.SubGroupID) AS Expr1
FROM dbo.tblForumSubGroups AS tblForumSubGroups_1

答案 2 :(得分:0)

我建议交叉申请,因为你可以用它做更多的事情......

SELECT t1.id,
   t1.GroupID,
   t1.SubGroupTitle,
   t1.SubGroupDesc,
   t2.val
FROM dbo.tblForumSubGroups AS t1
cross apply (SELECT COUNT(*)
         FROM dbo.tblForumPosts as t2
         WHERE t1.id = t2.SubGroupID) x(val)

答案 3 :(得分:0)

只是提供另一个答案,但我相信交叉申请可能是最好的选择:

SELECT 
    A.id, A.GroupID, A.SubGroupTitle, A.SubGroupDesc,
    B.IDCount AS Expr1
FROM dbo.tblForumSubGroups A 
INNER JOIN (
    Select SubGroupID, Count(ID) as IDCount
    from dbo.tblForumPosts
    Group By SubGroupID
) B On A.ID = B.SubGroupID