search

Home  >  Q&A  >  body text

Unable to drop index required by MySQL foreign key constraint

<p>I need to modify my existing database to add a column. Therefore, I also want to update the UNIQUE field to include that new column. I'm trying to drop the current index but I keep getting the error message <code>MySQL Cannot drop index needed in a foreign key constraint</code></p> <pre class="brush:php;toolbar:false;">CREATE TABLE mytable_a ( ID TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(255) NOT NULL, UNIQUE(Name) ) ENGINE=InnoDB; CREATE TABLE mytable_b ( ID TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(255) NOT NULL, UNIQUE(Name) ) ENGINE=InnoDB; CREATE TABLE mytable_c ( ID TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(255) NOT NULL, UNIQUE(Name) ) ENGINE=InnoDB; CREATE TABLE `mytable` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `AID` tinyint(5) NOT NULL, `BID` tinyint(5) NOT NULL, `CID` tinyint(5) NOT NULL, PRIMARY KEY (`ID`), UNIQUE KEY `AID` (`AID`,`BID`,`CID`), KEY `BID` (`BID`), KEY `CID` (`CID`), CONSTRAINT `mytable_ibfk_1` FOREIGN KEY (`AID`) REFERENCES `mytable_a` (`ID`) ON DELETE CASCADE, CONSTRAINT `mytable_ibfk_2` FOREIGN KEY (`BID`) REFERENCES `mytable_b` (`ID`) ON DELETE CASCADE, CONSTRAINT `mytable_ibfk_3` FOREIGN KEY (`CID`) REFERENCES `mytable_c` (`ID`) ON DELETE CASCADE ) ENGINE=InnoDB; mysql> ALTER TABLE mytable DROP INDEX AID; ERROR 1553 (HY000): Cannot drop index 'AID': needed in a foreign key constraint</pre> <p><br /></p>
P粉882357979P粉882357979589 days ago652

reply all(2)I'll reply

  • P粉056618053

    P粉0566180532023-08-15 11:27:29

    step 1

    List foreign keys (note that they are different from the index names)

    SHOW CREATE TABLE  <表名>

    The results will show the foreign key names.

    Format:

    CONSTRAINT `FOREIGN_KEY_NAME` FOREIGN KEY (`FOREIGN_KEY_COLUMN`) REFERENCES `FOREIGN_KEY_TABLE` (`id`),

    Step 2

    Delete (foreign key/primary key/key)

    ALTER TABLE <表名> DROP FOREIGN KEY <外键名称>

    Step 3

    Delete index.

    reply
    0
  • P粉043566314

    P粉0435663142023-08-15 00:33:14

    You must delete the foreign key. In MySQL, foreign keys automatically create an index on the table (this SO question is about this topic).

    ALTER TABLE mytable DROP FOREIGN KEY mytable_ibfk_1 ;

    reply
    0
  • Cancelreply