我有一个表
user_interactions
有 4 列:
user_1
user_2
type
timestamp
主键是
(user_1,user_2,type)
(user_2,user_1,type)
所以我所做的是:
drop primary key ...
add primary key (user_2,user_1,type)...
瞧...
问题是数据库位于服务器上。
因此,在我更新主键之前,许多重复项已经悄然出现,并且它们正在不断地出现。
该怎么办?
我现在想做的是删除重复项并保留最新的
timestamp
(这是表中的一列)。
然后以某种方式再次更新主键。
下次,使用单个“alter table”语句来更新主键。
alter table xx drop primary key, add primary key(k1, k2, k3);
修复问题:
create table fixit (user_2, user_1, type, timestamp, n, primary key( user_2, user_1, type) );
lock table fixit write, user_interactions u write, user_interactions write;
insert into fixit
select user_2, user_1, type, max(timestamp), count(*) n from user_interactions u
group by user_2, user_1, type
having n > 1;
delete u from user_interactions u, fixit
where fixit.user_2 = u.user_2
and fixit.user_1 = u.user_1
and fixit.type = u.type
and fixit.timestamp != u.timestamp;
alter table user_interactions add primary key (user_2, user_1, type );
unlock tables;
当您执行此操作时,锁应该会阻止进一步的更新。这需要多长时间显然取决于您的桌子的大小。
主要问题是是否有一些具有相同时间戳的重复项。
如果主键恰好是 auto_increment 值,则必须删除自增,然后删除主键,然后重新添加自增
ALTER TABLE `xx`
MODIFY `auto_increment_field` INT,
DROP PRIMARY KEY,
ADD PRIMARY KEY (new_primary_key);
然后添加回自动增量
ALTER TABLE `xx` ADD INDEX `auto_increment_field` (auto_increment_field),
MODIFY `auto_increment_field` int auto_increment;
然后将自动增量设置回之前的值
ALTER TABLE `xx` AUTO_INCREMENT = 5;
您也可以使用
IGNORE
关键字,例如:
update IGNORE table set primary_field = 'value'...............
插入学生(id) 价值观(1) 重复密钥更新 id=0;