简体   繁体   中英

How to alter a column which is a primary key in the table and a foreign key in another table in MySQL?

I want to run the following sql query:

ALTER TABLE USER MODIFY USER_ID int UNSIGNED NOT NULL AUTO_INCREMENT

But USER_ID is a foreign key on another table. What is the best way to change this column?

This is the error that I get:

Error Code: 1833. Cannot change column 'USER_ID': used in a foreign key constraint 'order_detail_ibfk_1' of table 'test.order_detail'

This has to be multistep

ALTER TABLE other_table DROP FOREIGN KEY fk_name
ALTER TABLE other_table MODIFY USER_ID int UNSIGNED NOT NULL
ALTER TABLE USER MODIFY USER_ID int UNSIGNED NOT NULL AUTO_INCREMENT
ALTER TABLE other_table ADD FOREIGN KEY ...

In MySQL 5.7, the server prohibits changes to foreign key columns that have the potential to cause loss of referential integrity. It also prohibits changes to the data type of such columns that may be unsafe. For example, changing VARCHAR(20) to VARCHAR(30) is permitted, but changing it to VARCHAR(1024) is not because that alters the number of length bytes required to store individual values. A workaround is to use ALTER TABLE ... DROP FOREIGN KEY before changing the column definition and ALTER TABLE ... ADD FOREIGN KEY afterward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM