dha*_*0us 95 mysql primary-key
我有一个user_interactions有4列的表:
user_1
user_2
type
timestamp
Run Code Online (Sandbox Code Playgroud)
主键是(user_1,user_2,type)
,我想改为(user_2,user_1,type)
所以我做的是:
drop primary key ...
add primary key (user_2,user_1,type)...
Run Code Online (Sandbox Code Playgroud)
瞧...
问题是数据库在服务器上是活的.
因此,在我更新主键之前,许多重复项已经悄悄进入,并且它们不断涌入.
该怎么办?
我现在要做的是删除重复项并保留最新的重复项timestamp(这是表中的一列).
然后以某种方式再次更新主键.
Mar*_*tin 211
下次,使用单个"alter table"语句更新主键.
alter table xx drop primary key, add primary key(k1, k2, k3);
Run Code Online (Sandbox Code Playgroud)
解决问题:
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;
Run Code Online (Sandbox Code Playgroud)
锁定应该在您执行此操作时停止进一步更新.这需要多长时间取决于你的桌子的大小.
主要问题是如果您有一些具有相同时间戳的重复项.
fra*_*ras 10
如果主键恰好是auto_increment值,则必须删除自动增量,然后删除主键,然后重新添加自动增量
ALTER TABLE `xx`
MODIFY `auto_increment_field` INT,
DROP PRIMARY KEY,
ADD PRIMARY KEY (new_primary_key);
Run Code Online (Sandbox Code Playgroud)
然后加回自动增量
ALTER TABLE `xx` ADD INDEX `auto_increment_field` (auto_increment_field),
MODIFY `auto_increment_field` int auto_increment;
Run Code Online (Sandbox Code Playgroud)
然后将自动增量设置回以前的值
ALTER TABLE `xx` AUTO_INCREMENT = 5;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150642 次 |
| 最近记录: |