通过连接3个SQL表查询每个祖父children、祖父children的计数

Query count of children, grandchildren of each grandfather by joining 3 SQL tables

我有以下 3 tables:

Parents table

id   names
------------
1     john
2     William

Children table

id  parent_id   names
----------------------
1     1          Thomas
2     1          Alfie
3     2          Henry

Grandchildren table 指向 Children table

id  parent_id   names
----------------------
1     3          Harry
2     1          Joseph
3     1          Adam

我想得到每个祖父的名字以及各自的计数 children 和祖父的计数 children。

我尝试了以下方法,但计数错误:

SELECT Parents.Id
      ,Parents.[name]
      ,COUNT(Children.Id) as children
      ,COUNT(Grandchildren.Id) as grandchildren 
  FROM Parents
  LEFT JOIN Children 
    ON Parents.Id = Children.ParentId
  LEFT JOIN Grandchildren
    ON Children.Id = Grandchildren.ParentId
  GROUP BY Parents.Id
          ,Parents.[name]

我可能做错了什么?

您应该计算每个父项的不同子项,因为每个子项的联接可能 return 多于 1 行。
因为这是您的查询,所以不需要计算不同的孙子,但如果您决定添加更多连接,那么您也应该这样做。

在任何情况下都使用关键字 DISTINCT(以及表格的别名以使代码更具可读性):

SELECT p.Id, p.[name], 
       COUNT(DISTINCT c.Id) children, 
       COUNT(DISTINCT g.Id) grandchildren 
FROM Parents p
LEFT JOIN Children c ON p.Id = c.ParentId
LEFT JOIN Grandchildren g ON c.Id = g.ParentId
GROUP BY p.Id, p.[name];

我认为您只是缺少一个 DISTINCT 关键字。你的查询应该像

select  Parents.Id, Parents.[name] , COUNT( DISTINCT Children.Id ) children, count(Grandchildren.Id) grandchildren 
from Parents
left join Children on Parents.Id = Children.ParentId
left join Grandchildren on Children.Id = Grandchildren.ParentId
group by Parents.Id, Parents.[name]

demo