Changing MySQL primary key when foreign key contraints exist(存在外键约束时更改 MySQL 主键)
问题描述
我有两个已经存在的表,看起来(部分)大致如下:
I have two already-existing tables which look (in part) roughly like this:
我想向 parent
添加一个新的自动递增整数 id
列并将其用作主键,同时仍保留 old_pk
作为唯一键并允许 child
等其他表在外键约束中引用它.不幸的是,简单地说 ALTER TABLE parent DROP PRIMARY KEY
不起作用:
I want to add a new auto-incrementing integer id
column to parent
and use it as the primary key instead, while still keeping old_pk
as a unique key and allowing other tables like child
to reference it in foreign key contraints. Unfortunately, simply saying ALTER TABLE parent DROP PRIMARY KEY
doesn't work:
错误代码:1025
将./data/#sql-4013_70f5e"重命名为./data/parent"时出错(错误号:150)
Error on rename of './data/#sql-4013_70f5e' to './data/parent' (errno: 150)
一些谷歌搜索表明这是由于来自 child
的现有外键引用.本质上,我需要一种方法来告诉 MySQL使用另一列作为主键,但不要忘记原始列的唯一键".除了从 child
中删除关键约束并在之后恢复它们之外,还有什么方法可以做到这一点?
Some googling suggests that this is due to the existing foreign key reference from child
. In essence, I need a way to tell MySQL "use this other column as the primary key, but don't forget the unique-key-ness of the original one". Is there any way to accomplish this, other than just dropping the key constraints from child
and reinstating them afterwards?
假设我必须就地更改表,而不是创建具有相同数据的副本并在以后交换它们.我在更改表格之前尝试过使用 SET FOREIGN_KEY_CHECKS = 0
,但它似乎没有帮助.
Assume that I must alter the tables in place, rather than creating copies with the same data and swapping them in later. I've tried using SET FOREIGN_KEY_CHECKS = 0
before altering the table, but it does not seem to help.
推荐答案
在删除主键之前给 old_pk 添加一个索引(甚至可以是唯一的):
Add an index (it could even be UNIQUE) to old_pk before dropping the primary key:
这篇关于存在外键约束时更改 MySQL 主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!