请教重复数据清理的sql,采纳后加分100

来源:百度知道 编辑:UC知道 时间:2024/05/02 22:32:26
table1中有字段id name
存放的信息如下
id name
100 和田路
101 和田路
102 张家村
103 和田路
在table2中有字段id name table1id
id name tableID
1000 50号 100
1001 51号 102
1002 52号 101
1003 53号 103
在这两个表中,第一个表中有虽然ID不重复,但是name有重复信息.
现在我要做的工作是:将table中的name的重复项删除,只保留ID最小的,就是id 100的和田路,然后在表二table2中,要把tableID中的101,103也改成100.
这个sql如何写?

你这个一条SQL处理不了.多一张表,2条SQL语句可以处理,以下仅供参考,SQL未经测试。
1、从table1抽取出name不重复的数据,存到table3:
select min(id) as id,name from table1 group by name
2、更改table2的tableID
update talbe2 set tableID = (select id from table3 where table3.name = (select name from table1 where id = talbe2.tableID))
where tableID not in (select id from table3)
如果table1和table2 的数据量很大(100M以上),那以上SQL语句建议不要使用,执行效率会很低。你可以写个程序来专门处理。

先把表2更新,因为表1如果先删掉,表2就没有根据来更新了。
update table2 set tableID=t.minid from (select name,min(id) minid from table1 group by name) t,table1 t1 where t1.id=table2.tableID and t1.name=t.name

再删除重复的table1数据
delete from table1 where id not in (select t1.id from table1 t1,(select name,min(id) minid from table1 group by name) t where t1.name=t.name and t1.id=t.minid)