1.给重复数据添加主键
在数据库中,有数条数据是重复没有,且这个表没有主键。在重复数据中,id也是重复,初步判断,是同步数据有误,将其他节点的数据同步过来了,造成id相同的重复数据。数据库是 postgresql
要求:删除重复数据,并添加主键
-- 1 创建序列
create sequence seq_temp_report increment by 1 minvalue 1 no maxvalue start with 1;
select nextval('seq_temp_report');
-- 2 将序列绑定到表的指定字段
alter table report_temp alter column attr10 set default nextval('seq_temp_report')
-- 3 给重复数据的表插入数据,其余字段的数据都相等,所以这时候插入一个字段不一样的值
-- 注意,这里select的字段不能包含attr10,否则这个字段插入的值不是序列中的值
insert into report_temp select distinct id, col1, col2 from (
select id from report temp group by id having count(id) > 1;
)
-- 4 删除重复数据
delete from report_temp where (attr10 is null or attr = '')
or id in (
select id from report_temp group by id having count(id) > 1
);
-- 5 删除 attr10 绑定的序列
alter table report alter column attr10 set default null;
drop sequence seq_temp_report;
update report_temp set attr10 = '' where attr is not null;
-- 6 添加主键
alter table report_temp add constraint 'pk_primary_key' primary key(id);