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

标签 mysql sql

仅当该行也是另一个表的子项时,我才尝试在表列中查找重复项,例如:

表 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 中具有相同类型和 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 行。

最佳答案

您似乎想要一对相同的 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 放入列表中。

关于mysql - 查找所有具有重复列的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36984099/

相关文章:

mysql - 在 MySql Workbench 中测试存储过程

MySQL 和 Entity Framework - 调用存储过程的应用程序返回 0 行受影响但相同的过程在终端中工作

python - 如何使用 fetchmany 将 mysql 表转储到 csv 中

php - 运行查询时总是获取 NULL

mysql - 优先选择SQL

mysql - 使用模数时索引是否会提高性能?

php - 检查时间(带时区)是否在给定的时间范围内

sql - PL/SQL 匿名 block 'Exact fetch returns more than requested number of rows'

php - SQL 查询未提供结果

mysql - "Inverse"限制?