今天遇到一个问题,数据表的数据有重复的,关键原因在于新增数据时,没有根据条件先判断数据是否存在,当数据存在时进行有关条件的更新,不存在时做新增数据。
对于表中已经存在的数据处理办法的方法:
1.先根据条件进行统计数据重复率。
2.查询那一些数据是重复的,将重复数据放在一张表中用于条件对比将源数据中的重复数据删除(mysql中使用一张表,sqlserver中可以使用临时表或者表变量存放数据)。
3.根据条件关联将重复数据删除。
可以先查询重复数据的总数:
select sum(count) from( select bidsectioncode,count(bidsectioncode) as count from businessdata.business_bidsection group by bidsectioncode having count>1 order by create_time desc ) as d;
查出数据库中的重复记录的数据中的一条,这个不难,很简单的,sql语句如下:
select * from businessdata.business_bidsection where bidsectioncode in (select bidsectioncode from businessdata.business_bidsection group by bidsectioncode having count(bidsectioncode) > 1) and id in (select min(id) from businessdata.business_bidsection group by bidsectioncode having count(bidsectioncode)>1)
这些都是不重复的,换句话说都是要保留的,不被删掉的,而其余与这些结果中name相同的应该被删掉。
也就是说将上边那个sql语句id后边加一个not ,查出来的结果就是要删掉的。
select * from businessdata.business_bidsection where bidsectioncode in (select bidsectioncode from businessdata.business_bidsection group by bidsectioncode having count(bidsectioncode) > 1) and id not in (select min(id) from businessdata.business_bidsection group by bidsectioncode having count(bidsectioncode)>1)
我把这些需要删掉的存到另外一个表里,然后我新建一个business_bidsection_test表,结构复制business_bidsection的结构就好了。
复制一个创建语句到test表中。
然后将重复数据添加到test表中,插入语句是:
insert into business_bidsection_test (select * from businessdata.business_bidsection where bidsectioncode in (select bidsectioncode from businessdata.business_bidsection group by bidsectioncode having count(bidsectioncode) > 1) and id not in (select min(id) from businessdata.business_bidsection group by bidsectioncode having count(bidsectioncode)>1));
那接下来做的就是删掉business_bidsection表里边与business_bidsection_test表的id相同的数据。
delete a.* from business_bidsection a, business_bidsection_test b where a.id = b.id ;
这样的结果就是完全不重复的,但是id是不连续的。
来源:https://www.cnblogs.com/kongxiaoshuang/p/6877454.html