SQL查找具有多个父记录的子项

时间:2016-07-22 17:48:14

标签: mysql sql

我有一种情况,我们已将重复数据插入到某些表中。

鉴于以下数据库模式,我想查找与表A中多于1条记录相关联的s_id和co_id组合的所有记录。突出显示的行是我正在寻找的行,基于找到我需要的重复项从表A中找到与重复记录相关联的id。

我可以通过s_id&组分组co_id确定潜在的重复项,但因为表B是1:M,这不完全准确。

Select c.s_id, c.co_id, Count(*)
from c 
    INNER JOIN b on c.b_id = b.id
    INNER JOIN a on a.id = b.a_id
Group By c.s_id, c.co_id
Having count(*) > 1;

ERD enter image description here

2 个答案:

答案 0 :(得分:2)

我想你只想要count(distinct)

Select c.s_id, c.co_id, Count(distinct a.id)
from c join
     b
     on c.b_id = b.id join
     a 
     on a.id = b.a_id
Group By c.s_id, c.co_id
having count(distinct a.id) > 1;

答案 1 :(得分:1)

戈登的回答将为您提供s_idco_id值。如果您需要将这些追溯到a,请尝试以下操作:

select distinct a.id
from
    a inner join b on b.a_id = a.id inner join c on c.b_id = b.id inner join
    (
        select c.s_id, c.co_id
        from a inner join b on b.a_id = a.id inner join c on c.b_id = b.id
        group by c.s_id, c.co_id
        having count(distinct a.id) > 1
    ) as dups
        on dups.s_id = c.s_id and dups.co_id = s.co_id