【问题标题】:SQL: How to find all parents where parents have children with given idSQL:如何找到父母有给定ID的孩子的所有父母
【发布时间】:2018-11-16 15:50:08
【问题描述】:

我有一个关于父/子联接表的问题。我有一个名为 parent_children 的连接表。该表包含一个 parent_id 和 child_id。像这样:

parent_id  | child_id
1            1
1            2
1            3
2            1
2            3
3            1
3            4

我想要的是在某个列表中找到所有有孩子的父母。所以假设列表包含 1 和 3,那么我想要 parent_id 1 和 2。如果列表包含 4,我想要 parent_id 3。我该怎么做?

【问题讨论】:

  • 孩子 1 有三个父母?

标签: sql join


【解决方案1】:

您可以使用group bywherehaving

select parent_id
from t
where child_id in (1, 3)
group by parent_id
having count(*) = 2;  -- "2" is the number of items in the list

这假定表中没有重复的父/子行。如果可以,请使用count(distinct child_id) = 2

【讨论】:

  • 这太棒了。感谢你的回答。我不知道你到底是怎么想到的。
【解决方案2】:

因此,您基本上需要计算输入的 IN 列表中出现的次数。 以下内容可以提供帮助。

create table parent_children(parent_id int, child_id int)


insert into parent_children values(1,1)
insert into parent_children values(1,2)
insert into parent_children values(1,3)
insert into parent_children values(2,1)
insert into parent_children values(2,3)
insert into parent_children values(3,1)
insert into parent_children values(3,4)



with list_data
  as(select *
       from (values(1),(3))as t(x)
    )
   select a.x          
     from list_data a
left join parent_children b
       on a.x=b.child_id
  group by a.x
having count(*) = count(distinct b.parent_id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多