繁体   English   中英

一对多关系需要所有记录中的所有记录来匹配条件

[英]One to many relationship needs all of the many records to match a condition

这两个表之间存在一对多关系:

p2c {
    parent_id,
    child_id
}

child {
    child_id, -- pk
    count1,
    count2
}

如果我这样做:

select distinct parent_id from p2c 
join child on p2c.child_id = child.child_id
where count1 = count2

我得到父母,其中一个孩子的数目相等。 我如何获得其所有子代数均相等的父代?

您可以按以下方式使用GROUP BY / HAVING:

select  parent_id 
from    p2c 
        join child on p2c.child_id = child.child_id
group by parent_id
having count(case when count1 = count2 then 1 end) = count(*);

这基本上是对count1 = count2行进行计数,并且仅返回parent_id s(该计数与总数相同)

首先使用派生表,以获取匹配的行数和行数:

  select
    *
    from
    pc2
    join
    (
    select
    child_id,
    count1,
    count2,
    count(child_id) as NUM_ROWS,
    count(case when count1 = count2 then 1 else null) as NUM_MATCHES
    from child
    group by child_Id
    ) child
    on pc2.child_id = child.child_id
    where child.num_rows = num_matches

您将孩子和父母混在一起有点令人困惑。 一个孩子应该指称它的父母,而不是相反。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM