mysql 修改外键约束列_无法更改外键约束中使用的列

bd96500e110b49cbb3cd949968f18be7.png

I got this error when i was trying to alter my table.

Error Code: 1833. Cannot change column 'person_id': used in a foreign key constraint 'fk_fav_food_person_id' of table 'table.favorite_food'

Here is my CREATE TABLE STATEMENT Which ran successfully.

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)

);

Then i tried to execute this statement and i got the above error.

ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;

解决方案

The type and definition of foreign key field and reference must be equal.

This means your foreign key disallows changing the type of your field.

One solution would be this:

LOCK TABLES

favorite_food WRITE,

person WRITE;

ALTER TABLE favorite_food

DROP FOREIGN KEY fk_fav_food_person_id,

MODIFY person_id SMALLINT UNSIGNED;

Now you can change you person_id

ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;

recreate foreign key

ALTER TABLE favorite_food

ADD CONSTRAINT fk_fav_food_person_id FOREIGN KEY (person_id)

REFERENCES person (person_id);

UNLOCK TABLES;

EDIT:

Added locks above, thanks to comments

You have to disallow writing to the database while you do this,

otherwise you risk data integrity problems.

I've added a write lock above

All writing queries in any other session than your own ( INSERT, UPDATE, DELETE ) will wait till timeout or UNLOCK TABLES; is executed

EDIT 2: OP asked for a more detailed explanation of the line "The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field."

Corresponding columns in the foreign key and the referenced key must

have similar internal data types inside InnoDB so that they can be

compared without a type conversion. The size and sign of integer types

must be the same. The length of string types need not be the same. For

nonbinary (character) string columns, the character set and collation

must be the same.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值