Drop foreign key only if it exists

前端 未结 7 2061
清歌不尽
清歌不尽 2021-02-05 01:37

I\'m on a MySQL database.

I\'m doing this, but it doesn\'t work.

ALTER TABLE `object` DROP FOREIGN KEY IF EXISTS `object_ibfk_1`;

I\'ve

7条回答
  •  别那么骄傲
    2021-02-05 02:38

    IF EXISTS(
                  SELECT *
                  FROM INFORMATION_SCHEMA.STATISTICS
                  WHERE INDEX_SCHEMA = DATABASE()
                        AND TABLE_NAME='myTable'
                        AND INDEX_NAME = 'myIndex')
            THEN
    
                ALTER TABLE `myTable` DROP FOREIGN KEY `myForeignKey`;
    
                ALTER TABLE `myTable` DROP INDEX `myIndex` ;
    
            END IF;
    

    When you create a foreign key constraint, mysql will automatically create an index on the referenced column. The example above shows how to check for an index in the INFORMATION_SCHEMA, but there is much more information for you to check out in the information schema. Your index name seems to indicate that it was created for a FK, so you'd have to drop the FK first, then drop the index. If you create the foreign key again, mysql will create the index again. It needs an index to enforce referential integrity without having to do a table scan.

    If your intention was to create a new index that contains the same column, you'd have to create that index first (with this column, the one that will be used as a FK, being the first in the list of columns specified for the index). Now you can add your FK back and mysql will be happy to use the new index without creating another one.

    Edit: to view indexes quickly simply execute SHOW INDEXES FROM myTable;

提交回复
热议问题