【问题标题】:SQL - how to get all rows in parent based on number of children of that parent?SQL - 如何根据父级的子级数获取父级中的所有行?
【发布时间】:2017-12-08 17:52:11
【问题描述】:

我有 2 张桌子:

  • 父表:id、名称
  • 子表:id、name、id_parent

现在,我想列出父表中的行,子表的行数为 3。

【问题讨论】:

标签: sql postgresql select


【解决方案1】:

我像这样编辑我的查询。

select p.*, count(c.id)
from parents p
join children c
     on c.id_parent = p.id
group by p.id
having count(*) = 3

还好吗? jarlh

【讨论】:

  • 看起来不错!
  • 我发现了一个遗漏的返回数据。如果我使用 count(*)=0,它返回空。
  • 如果你想包括没有孩子的父母,请切换到LEFT JOIN。并做having count(c.id) = 0
【解决方案2】:

可以通过多种方式完成。最简单的可能是 WHERE 子句中的相关子查询来计算子项的数量:

select *
from parents p
where (select count(*) from children c
       where c.id_parent = p.id) = 3

GROUP BY,与HAVING

select p.*
from parents p
join children c
     on c.id_parent = p.id
group by p.id
having count(*) = 3

【讨论】:

  • 哦,这是一个很好的解决方案。谢谢贾尔。顺便说一句,如果我想获得具有该结果的孩子的数量,我该如何编辑查询?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-20
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多