查找具有重复列的所有子项

时间:2016-05-02 13:51:01

标签: mysql sql

我试图在表列中找到重复项,只要该行也是另一个表ex的子项:

表1列

id
Type

表2栏

id
table1Id
table3Id

示例数据:

table 1:
    id    Type
    1      aType
    2      myType
    3      myType
    4      myType
    5      myType
    6      myType

table 2:
    id    table1Id    table3Id
    1        1            1
    2        2            1
    3        4            2
    4        5            1
    5        6            2

结果我想:( table1中的行具有相同的Type和table3Id)

table1Id  table1Type table3Id
   2        myType     1
   5        myType     1
   4        myType     2
   6        myType     2

查询我试过:

select t1.id as table1Id, t1.type as table1Type, t2.table3Id 
from table1 t1 inner join
    table2 t2
    on t1.id = t2.table1Id inner join
    table1 a 
    on t1.Type = a.Type and a.id <> t1.id
where t1.Type = 'myType' ;

上面的查询为我提供了相同行的数百次重复,返回了大约500,000行。

2 个答案:

答案 0 :(得分:1)

您似乎希望成对的table3idtable1type成对。这是一种以稍微不同的格式返回结果的方法:

select t2.table3id, t1.type, group_concat(t1.id) as table1ids
from table1 t1 join
     table2 t2
     on t1.id = t2.table1id
group by t2.table3id, t1.type
having count(*) > 1;

这会将id放在列表中。

答案 1 :(得分:0)

这对我来说很好用:

drop table if exists table1;
drop table if exists table2;

create table test_delete.table1 as    
select  1   id  , 'aType' typ union all
select  2      ,'myType' union all
select  3      ,'myType' union all
select  4      ,'myType' union all
select 5      ,'myType' union all
select 6      ,'myType';

create table test_delete.table2 as    

select    1  id     , 1     table1Id     ,  1 table3Id union all
select  2        ,2           , 1 union all
select   3        ,4           , 2 union all
select   4        ,5           , 1 union all
select   5        ,6           , 2;

select * from table1; 

select 
    t1.id, t1.typ, t2.table3Id
from
    table1 t1
        inner join
    table2 t2 on t1.id = t2.table1Id
where
    t1.typ = 'myType'
order by t2.table3Id;