一对多关系需要所有许多记录以匹配条件

时间:2013-11-06 20:15:54

标签: sql

我与这两张桌子有一对多的关系:

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

我得到父母,其中一个孩子的计数相等。如何让父母的所有子女的计数相等?

3 个答案:

答案 0 :(得分:4)

您可以按如下方式使用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,其中此计数与总数相同

答案 1 :(得分:1)

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

  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

答案 2 :(得分:0)

你混淆了孩子和父母,这有点令人困惑。孩子应该引用它的父母,而不是相反。