Problem adding Foreign Key using Alter Table with existing MYSQL Database - can't add it! Help!

前端 未结 6 1200
情话喂你
情话喂你 2020-12-10 14:40

I have a production database where I have renamed several column\'s that are foreign keys. Obviously mysql makes this a real pain to do in my experience.

My solution

6条回答
  •  自闭症患者
    2020-12-10 15:44

    @egervari You wrote - My solution was to drop all the indexes and foreign keys, rename the id columns, and then re-add the indexes and foreign keys.

    Agree with you. But it might be that something went wrong. I reproduced the error, and (in my case) fixed it.

    I'd suggest you to run OPTIMIZE TABLE command for table where column was renamed. Documentation says - For InnoDB tables, OPTIMIZE TABLE is mapped to ALTER TABLE, which rebuilds the table to update index statistics and free unused space in the clustered index.


    One more solution:

    Drop unique key in the referenced table (key that is used by foreign key, in your case it is a primary key). Then add new foreign key and recreate droped unique key.


    One more solution:

    Try to add and drop new column to the referenced table, then try to create your foreign key.

    ALTER TABLE company ADD COLUMN column1 VARCHAR(255) DEFAULT NULL;
    ALTER TABLE company DROP COLUMN column1;
    

提交回复
热议问题