查询儿童,每个祖父的孙子,加入3 SQL桌子
我有以下 3 个表:
父母表
id names
------------
1 john
2 William
儿童表
id parent_id names
----------------------
1 1 Thomas
2 1 Alfie
3 2 Henry
孙子表,它指向
id parent_id names
----------------------
1 3 Harry
2 1 Joseph
3 1 Adam
我想要获取的 儿童表
每个祖父的名字以及各自的孩子数和孙子数。
我尝试了以下操作,但计数错误:
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]
我可能做错了什么?
I have the following 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 which points to Children table
id parent_id names
----------------------
1 3 Harry
2 1 Joseph
3 1 Adam
I want to get the names of each grandfather with respective count of children and count of grandchildren.
I tried the following, but got wrong counts:
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]
What may I be doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该计算每个父母的不同孩子,因为加入可能会为每个孩子返回1行以上。
由于是您的查询,因此无需计算不同的孙子,但是如果您决定添加更多的连接,那么您也应该这样做。
在任何情况下,请使用关键字
dintive
(和别名表使代码更易读的表):You should count the distinct children for each parent because the joins may return more than 1 row for each child.
As it is your query there is no need to count distinct grandchildren but if you decide to add more joins then you should also do that too.
In any case use the keyword
DISTINCT
(and aliases for the tables to make the code more readable):我认为您只是缺少一个 DISTINCT 关键字。您的查询应该类似于
演示
I think you are just missing a DISTINCT keyword . your query should be like
see demo