【问题标题】:Updating MySQL primary key更新 MySQL 主键
【发布时间】:2011-01-21 10:40:45
【问题描述】:

我有一张表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(表中的一列)。

然后以某种方式再次更新主键。

【问题讨论】:

  • 我突然为我暗中诅咒的每一个 DBA 感到难过...
  • 下次添加与主键同列的唯一键,然后更新主键
  • @Ignacio,它存在于服务器上,但这是一个备份-备份服务器:-)。我不是 DBA,但我不会在真正的实时服务器上尝试这个东西 :-)
  • @knittl,是的,我现在就是这么想的,虽然很晚了:-)
  • @pixeline: 这是一个复合主键。

标签: mysql primary-key


【解决方案1】:

如果主键恰好是 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;

【讨论】:

    【解决方案2】:

    下一次,使用单个“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;
    

    在您执行此操作时,锁应该会阻止进一步的更新。这需要多长时间显然取决于您的桌子的大小。

    主要问题是您是否有一些具有相同时间戳的重复项。

    【讨论】:

      【解决方案3】:

      您也可以使用IGNORE 关键字,例如:

       update IGNORE table set primary_field = 'value'...............
      

      【讨论】:

        猜你喜欢
        • 2015-06-21
        • 1970-01-01
        • 2015-05-17
        • 2019-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-08
        相关资源
        最近更新 更多