sql-server - 如何删除在 SQL Server 中作为外键引用的重复记录?
问题描述
我在 SQL Server 中有一种情况,我有重复的数据,但在一个引用为外键的表中。这些表看起来像:
- 模板(id、名称、描述、作者)
- TemplatesToAttachements (id, templateId, attachmentId)
- 附件(id、描述、作者、目的)
我注意到的是我已经复制Attachments
了一个Template
. 查看数据库,由于一个错误,我看到为相同TemplatesToAttachements
的重复添加了多条记录。Attachments
Template
样本:
有人可以帮我删除那些TemplatesToAttachements
重复的额外记录Attachments
(重复的附件是指两个具有相同描述、作者和目的的附件)。
我在这里写了一个表格样本:
http://www.sqlfiddle.com/#!18/4ef0a0
非常感谢。
解决方案
尝试使用这个:
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
推荐阅读
- vba - 为什么从最新的电子邮件跳过文件循环进入电子邮件收件箱?
- c# - 如果我从数据库中删除外键约束,实体框架的导航属性会起作用吗?
- spring-boot - 在 Spring Cloud 中使用 @RefreshScope 重新加载弹簧属性时出错
- c# - 在代码中使用 System.Data.OleDb 命名空间时找不到 OleDbConnection
- tensorflow - 如何在自定义 keras 层中使用 keras 层
- android - 如何在android中播放缓存的字节数组
- html - 如何下移我的内容?该部分一直重叠
- c# - ElasticSearch 匹配 int 和 string 列表
- slack - 使用 Slack Bot 提及访客?
- javascript - Javascript 不显示从 PHP 和 SQL Server 获得的数据