Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't add AUTO_INCREMENT on existing column because of foreign key

I have primary key column, which has some external foreign key references. Very usual. I forgot to add AUTO_INCREMENT for it. Now I execute

ALTER TABLE chat.users CHANGE COLUMN user_id user_id INT(11) NOT NULL AUTO_INCREMENT ;

(PRIMARY KEY was defined separately)

it tells something about fk ERROR 1833: Cannot change column 'user_id': used in a foreign key constraint 'fk_chats_users' of table 'chat.chats'

I can't figure out why fk bother something about it's reference AUTO_INCREMENT.

like image 341
user3537411 Avatar asked Mar 26 '15 13:03

user3537411


People also ask

Can I add auto increment to existing column MySQL?

You can add auto_increment to a column in MySQL database with the help of ALTER command.

Does auto increment have to be primary key?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How can add auto increment to column in SQL Server?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

Is it possible to set a foreign key as auto increment?

A foreign key is a link to a specific record in another table (or another record in the same table). Creating a foreign key field that is auto-incrementing would create a link to an arbitrary (and possibly non-existent) record, which would defeat the whole purpose of having a foreign key in the first place.


1 Answers

The reason the FK bothers about your changes is because you are trying to alter it and is used in a constraint, remember that you are able to alter the data type.

So if you want to make the change to the FK, check this answer (remember to lock the tables before if you are making the change in a production environment).

like image 183
Leandro Carracedo Avatar answered Oct 02 '22 08:10

Leandro Carracedo