MySQL Removing Some Foreign keys

前端 未结 11 622
太阳男子
太阳男子 2020-11-28 01:55

I have a table whose primary key is used in several other tables and has several foreign keys to other tables.

CREATE TABLE location (
   locationID INT NOT         


        
相关标签:
11条回答
  • 2020-11-28 02:23

    first need to get actual constrain name by this query

    SHOW CREATE TABLE TABLE_NAME
    

    This query will result constrain name of the foreign key, now below query will drop it.

    ALTER TABLE TABLE_NAME DROP FOREIGN KEY COLUMN_NAME_ibfk_1
    

    last number in above constrain name depends how many foreign keys you have in table

    0 讨论(0)
  • 2020-11-28 02:25

    You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.

    But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:

    SHOW CREATE TABLE region; This should show you a row ,at left upper corner click the +option ,the click the full text raio button then click the go .there you will get the name of the index, something like this:

    CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION Now simply issue an:

    alter table region drop foreign key region_ibfk_1;

    or

    more simply just type:- alter table TableName drop foreign key TableName_ibfk_1;

    remember the only thing is to add _ibfk_1 after your tablename to make like this:- TableName_ibfk_1

    0 讨论(0)
  • 2020-11-28 02:27

    The foreign keys are there to ensure data integrity, so you can't drop a column as long as it's part of a foreign key. You need to drop the key first.

    I would think the following query would do it:

    ALTER TABLE assignmentStuff DROP FOREIGN KEY assignmentIDX;
    
    0 讨论(0)
  • 2020-11-28 02:30

    As explained here, seems the foreign key constraint has to be dropped by constraint name and not the index name. The syntax is:

    alter table footable drop foreign key fooconstraint
    
    0 讨论(0)
  • 2020-11-28 02:34

    Check what's the CONSTRAINT name and the FOREIGN KEY name:

    SHOW CREATE TABLE table_name;
    

    Remove both the CONSTRAINT name and the FOREIGN KEY name:

    ALTER TABLE table_name
      DROP FOREIGN KEY the_name_after_CONSTRAINT,
      DROP KEY the_name_after_FOREIGN_KEY;
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题