MySQL 1062-键“ PRIMARY”的条目“ 0”重复
我在MySQL 5.5.24中有下表
DROP TABLE IF EXISTS `momento_distribution`;CREATE TABLE IF NOT EXISTS `momento_distribution`
  (
     `momento_id`       INT(11) NOT NULL,
     `momento_idmember` INT(11) NOT NULL,
     `created_at`       DATETIME DEFAULT NULL,
     `updated_at`       DATETIME DEFAULT NULL,
     `unread`           TINYINT(1) DEFAULT '1',
     `accepted`         VARCHAR(10) NOT NULL DEFAULT 'pending',
     `ext_member`       VARCHAR(255) DEFAULT NULL,
     PRIMARY KEY (`momento_id`, `momento_idmember`),
     KEY `momento_distribution_FI_2` (`momento_idmember`),
     KEY `accepted` (`accepted`, `ext_member`)
  )
ENGINE=InnoDB
DEFAULT CHARSET=latin1;
它具有大量数据,并且其他两个表具有ondelete=restrict和并具有多对一关系onupdate=restrict。
现在,我需要更改结构并在表中引入单独的主键,同时仍保留现有的关系和数据。为此,我执行了以下查询:
ALTER TABLE  `momento_distribution` ADD  `id` INT( 11 ) NOT NULL FIRST;ALTER TABLE  `momento_distribution` DROP PRIMARY KEY , ADD PRIMARY KEY (  `id` );
不幸的是,我的第二次查询失败,并出现以下错误:
1062-键“ PRIMARY”的条目“ 0”重复
有人可以指出这个问题吗?我想问题是现有的关系,但是我不想丢失具有数千行的现有关系或数据。有什么方法可以做到这一点而又不会丢失数据吗?
通过查看数据,我得到了新创建的列中具有值‘0’。由于重复的记录(在新的主键中),这可能不允许更改主键。
我有8,000多行,因此无法手动更改。有什么方法可以分配rowid给新的主键吗?
回答:
在mysql控制台中运行以下查询:
SHOW CREATE TABLE momento_distribution检查看起来像这样的行
CONSTRAINT `momento_distribution_FK_1` FOREIGN KEY (`momento_id`) REFERENCES `momento` (`id`)可能会有所不同,我只是猜测可能会是什么。如果您在’momento_id’和’momento_idmember’上都具有外键,则将获得两个外键名称。下一步是删除外键。运行以下查询:
ALTER TABLE momento_distribution DROP FOREIGN KEY momento_distribution_FK_1ALTER TABLE momento_distribution DROP FOREIGN KEY momento_distribution_FK_2
确保将外键名称更改为您从CREATE
TABLE查询中获得的名称。现在,您没有任何外键,因此可以轻松删除主键。请尝试以下操作:
ALTER TABLE  `momento_distribution` DROP PRIMARY KEY添加所需的列,如下所示:
ALTER TABLE  `momento_distribution` ADD  `id` INT( 11 ) NOT NULL  PRIMARY KEY AUTO_INCREMENT FIRST该查询还会添加数字,因此您无需依赖@rowid。现在,您需要将外键添加回前面的列。为此,首先创建以下索引:
ALTER TABLE  `momento_distribution` ADD INDEX (  `momento_id` )ALTER TABLE  `momento_distribution` ADD INDEX (  `momento_idmember` )
现在添加外键。根据需要更改参考表/列:
ALTER TABLE  `momento_distribution` ADD FOREIGN KEY ( `momento_id`) REFERENCES  `momento` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT ALTER TABLE  `momento_distribution` ADD FOREIGN KEY ( `momento_idmember`) REFERENCES  `member` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
希望能有所帮助。如果您遇到任何错误,请使用参考表的结构以及所得到的错误代码来编辑问题。
以上是 MySQL 1062-键“ PRIMARY”的条目“ 0”重复 的全部内容, 来源链接: utcz.com/qa/420964.html








