【发布时间】:2013-03-11 08:40:04
【问题描述】:
使用 SQL Server 2008。我正在尝试删除表中的一些重复行。下面列出了相关的表格和列:
ItemTable
----------
Id - autoincrement, PK
ItemLabel - the actual identifier of the items
Linktable
----------
Id - autoincrement, PK
ItemId - the Id from ItemTable
RelatedItemId - the Id from RelatedItemTable
RelatedItemTable
------
no need to touch this with the query..
所以链接表不包含项目的实际id,而是两个表的运行行号
需要实现什么:ItemTable 包含具有重复 ItemLabel 的行,其中另一个列在链接表中(带有 Id 列的值),而另一个则没有。必须从 ItemTable 中删除未链接的那些。我知道如何使用 count 和 group by 选择重复的行,但无法弄清楚如何仅删除链接表中不存在的行。 ItemTable 还包含没有关系的重复项,其中一个必须保留(不管是哪个)。
http://www.sqlfiddle.com/#!3/9d181 这是一个带有虚拟数据的 SQL 小提琴。
附:不要问为什么链接表使用正在运行的 id 而不是实际的 id(可能是 PK 的)......这是一个遗留系统。
【问题讨论】:
标签: sql sql-server sql-delete