【问题标题】:How to delete duplicate rows in a table based on what is supposed to be a unique column referring to a table in another database如何根据引用另一个数据库中表的唯一列删除表中的重复行
【发布时间】:2020-01-27 14:26:54
【问题描述】:
Table A

LoginID|FacilityID|LoginName|PersonID|DateOfBirth|
    111|        20| Person_A|     101| 01/01/1990|
    212|        20| Person_B|     230| 02/02/1991|
    456|        20| Person_C|     101| 03/03/1992|
    987|        20| Person_A|     808| 01/01/1990|
Table B

PersonID|FacilityID|LastName|FirstName|DateOfBirth|
     101|        20|   Stone|     Beth| 03/03/1992|
     230|        20|   Jones|      Bob| 02/02/1991|
     808|        20|   Brown|     Jack| 01/01/1992|

在表 A 中,PersonID 是指表 B 中的另一个数据库,在这里应该是唯一的。由于某些原因,它不是,使用 PersonID 和 FacilityID 作为输入参数的存储过程正在为该重复 PersonID 的实例返回多行。我想删除表 A 中的顶部记录,因为它不属于通过将其与 PersonID 应该是什么进行比较。

我曾考虑将此处的 PersonID 和 DOB 与表 B 进行比较,并删除不匹配的记录,但是,我还没有想出办法来做到这一点。

【问题讨论】:

  • 请向我们展示其他表中的示例数据。

标签: sql sql-server tsql sql-delete


【解决方案1】:

我了解到您想删除 other 表中没有对应记录的记录,PersonIdDateOfBirth 相同。

如果是这样,您可以使用反left join,如下所示:

delete t
from mytable t
left join myothertable t1 
    on t1.PersonId = t.PersonId and t1.DateOfBirth = t.DateOfBirth
where t1.personId is null

【讨论】:

    【解决方案2】:

    GMB 的回答很好。不过,我认为not exists 是一种更自然的方法:

    delete a
        from a
        where not exists (select 1
                          from b
                          where b.personid = a.personid and b.dob = a.dob
                         );
    

    您可能还想在比较中包含facilityid

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多