How can I compare two tables and delete the duplicate rows in SQL?

冷暖自知 提交于 2019-12-03 03:33:48

Well, at some point you're going to have to check all the columns - might as well get joining...

DELETE a
FROM a  -- first table
INNER JOIN b -- second table
      ON b.ID = a.ID
      AND b.Name = a.Name
      AND b.Foo = a.Foo
      AND b.Bar = a.Bar

That should do it... there is also CHECKSUM(*), but this only helps - you'd still need to check the actual values to preclude hash-conflicts.

If you're using SQL Server 2005, you can use intersect:

delete * from table1 intersect select * from table2

I think the psuedocode below would do it..

DELETE FirstTable, SecondTable
FROM FirstTable
FULL OUTER JOIN SecondTable
ON FirstTable.Field1 = SecondTable.Field1
... continue for all fields
WHERE FirstTable.Field1 IS NOT NULL
AND SecondTable.Field1 IS NOT NULL

Chris's INTERSECT post is far more elegant though and I'll use that in future instead of writing out all of the outer join criteria :)

I would try a DISTINCT query and do a union of the two tables.

You can use a scripting language like asp/php to format the output into a series of insert statements to rebuild the table the resulting unique data.

try this:

DELETE t1 FROM t1 INNER JOIN t2 ON t1.name = t2.name WHERE t1.id = t2.id
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!