代码之家  ›  专栏  ›  技术社区  ›  Melz

如何比较两个配置单元表记录

  •  1
  • Melz  · 技术社区  · 7 年前

    我有两张表Core和BKP。表BKP包含重复的数据。但Core包含相同的数据,没有重复数据。

    两个表的主键是4个字段(1、2、3、4)的组合。

    但在运行一些脚本之后,核心表中的一些记录丢失了。

    如何从Core表中找出遗漏的记录(遗漏的记录肯定存在于BKP中,但有重复记录)。

    1 回复  |  直到 7 年前
        1
  •  0
  •   leftjoin    7 年前

    使用不存在:

    Select b.PK1,b.PK2,b.PK3,b.PK4 --Primary key from BKP missed in CORE
     from 
    (--select all PK existing in BKP
      select 
          distinct
          b.PK1,b.PK2,b.PK3,b.PK4 --Primary key from BKP
      from BKP b) b
    where not exists(select 1 from CORE c 
                      where c.PK1=b.PK1 
                        and c.PK2=b.PK2
                        and c.PK3=b.PK3
                        and c.PK4=b.PK4
                    )
    

    使用左连接:

        Select b.PK1,b.PK2,b.PK3,b.PK4 --Primary key from BKP missed in CORE
         from 
        (--select all PK existing in BKP
          select 
              distinct
              b.PK1,b.PK2,b.PK3,b.PK4 --Primary key from BKP
          from BKP b
        ) b
         left join 
                   (select c.PK1,c.PK2,c.PK3,c.PK4 --Primary key from CORE
                      from CORE c 
                    ) c 
               on c.PK1=b.PK1 
                  and c.PK2=b.PK2
                  and c.PK3=b.PK3
                  and c.PK4=b.PK4
      where c.PK1 is null --absent in CORE