首页 > 解决方案 > 如何删除在 SQL Server 中作为外键引用的重复记录?

问题描述

我在 SQL Server 中有一种情况,我有重复的数据,但在一个引用为外键的表中。这些表看起来像:

我注意到的是我已经复制Attachments了一个Template. 查看数据库,由于一个错误,我看到为相同TemplatesToAttachements的重复添加了多条记录。AttachmentsTemplate

样本:

有人可以帮我删除那些TemplatesToAttachements重复的额外记录Attachments(重复的附件是指两个具有相同描述、作者和目的的附件)。

我在这里写了一个表格样本:

http://www.sqlfiddle.com/#!18/4ef0a0

非常感谢。

标签: sql-server

解决方案


尝试使用这个:

DELETE TemplatesToAttachements
FROM (
    SELECT Rn = ROW_NUMBER OVER (PARTITION BY description, author, purpose ORDER BY id),
           id
    FROM Attachment     
) AS A
INNER JOIN TemplatesToAttachements ON TemplatesToAttachements.attachmentId = A.Id
WHERE Rn > 1


推荐阅读