【问题标题】:Compare two table and find missing row比较两个表并找到缺失的行
【发布时间】:2021-12-23 10:10:10
【问题描述】:

我有两个简单的表格:

表 1:

id , h_id, role, l_name
1 , 2, 3, test1
1, 2, 4, test1

表2:

id , h_id, role, l_name
1 , 2, 3, test1
1 , 2, 3, test2

我们没有任何主键或外键可供比较。 id , h_id, role, 可能在两个表中都有相同的数据,但 l_name 可能不同。它也可以是其他列。

比较上述情况的最佳方法是什么?

【问题讨论】:

  • 做一个union 应该给你独特的数据。
  • 2 个带有 WHERE NOT EXISTS 的单独查询 - 第一个查询搜索 table1 中 table2 中不存在的行,第二个查询解决后向任务。长列列表(最佳 - 用于比较的所有列)的复合索引的存在将得到改善。
  • 您的预期结果是什么?

标签: mysql sql teradata


【解决方案1】:

如果我理解您的情况,您将能够从 table1 和 table2 中分离出不匹配的数据?这是 ?所以你可以试试这个查询:

select t1.id, t1.h_id,t1.role, t1.l_name, t2.id, t2.h_id,t2.role, 
  t2.l_name from table1 t1
left join table2 t2 
on t1.id = t2.id and t1.h_id =t2.h_id and t1.role=t2.role and   t1.l_name=t2.l_name
where t2.id is null
union
select t2.id, t2.h_id, t2.role, t2.l_name, t1.id, t1.h_id, t1.role, 
  t1.l_name from table1 t2
right join table2 t1
on t1.id = t2.id and t1.h_id = t2.h_id and t1.role=t2.role and t1.l_name = t2.l_name 
where t2.id is null;

【讨论】:

    【解决方案2】:

    我会使用 MINUS 运算符:

    Select * from table1
    Minus
    Select * from table2
    

    然后以另一种方式重复

    【讨论】:

      猜你喜欢
      • 2017-08-28
      • 1970-01-01
      • 2011-12-21
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 2022-07-27
      相关资源
      最近更新 更多