[英]Unable to alter table with foreign key
My two empty tables: 我的两个空表:
CREATE TABLE person (
person_id SMALLINT UNSIGNED,
fname VARCHAR(20),
lname VARCHAR(20),
gender ENUM('m', 'f'),
birth_date DATE,
street VARCHAR(30),
city VARCHAR(20),
state VARCHAR(20),
country VARCHAR(20),
postal_code VARCHAR(20),
CONSTRAINT pk_person PRIMARY KEY (person_id)
);
create TABLE favorite_food (
person_id SMALLINT UNSIGNED,
food VARCHAR(20),
CONSTRAINT pk_favorite_food PRIMARY KEY (person_id, food),
CONSTRAINT fk_fav_food_person_id FOREIGN KEY (person_id) REFERENCES person (person_id)
);
Needed modification: 需要修改:
ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;
Result: 结果:
ERROR 1833 (HY000): Cannot change column 'person_id': used in a foreign key constraint 'fk_fav_food_person_id' of table 'tom.favorite_food' 错误1833(HY000):无法更改列“ person_id”:用于表“ tom.favorite_food”的外键约束“ fk_fav_food_person_id”
Why is this and is there a way around this without dropping the tables and redefining them? 为什么会这样,并且有解决此问题的方法而无需删除表并重新定义它们?
This is probably because there already is data in person.person_id in any rows (NOT NULL). 这可能是因为在任何行中person.person_id中已经有数据(NOT NULL)。 You can circumvent this by disabling foreign key checks 您可以通过禁用外键检查来规避此问题
I believe the best way to handle this is to drop the foreign key reference from favorite_food, alter the column in person and then recreate the foreign key reference. 我认为处理此问题的最佳方法是从“ favourite_food”中删除外键引用,亲自更改列,然后重新创建外键引用。 That will properly recreate the index on which the key depends. 这样可以正确地重新创建键所依赖的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.