How to remove constraints from my MySQL table?

前端 未结 12 1373
北恋
北恋 2020-11-30 18:03

I want to remove constraints from my table. My query is:

ALTER TABLE `tbl_magazine_issue` 
DROP CONSTRAINT `FK_tbl_magazine_issue_mst_users`
<
相关标签:
12条回答
  • 2020-11-30 18:52

    To add a little to Robert Knight's answer, since the title of the post itself doesn't mention foreign keys (and since his doesn't have complete code samples and since SO's comment code blocks don't show as well as the answers' code blocks), I'll add this for unique constraints. Either of these work to drop the constraint:

    ALTER TABLE `table_name` DROP KEY `uc_name`;
    

    or

    ALTER TABLE `table_name` DROP INDEX `uc_name`;
    
    0 讨论(0)
  • 2020-11-30 18:53

    Mysql has a special syntax for dropping foreign key constraints:

    ALTER TABLE tbl_magazine_issue
      DROP FOREIGN KEY FK_tbl_magazine_issue_mst_users
    
    0 讨论(0)
  • 2020-11-30 18:53
    1. Go to structure view of the table
    2. You will see 2 option at top a.Table structure b.Relation view.
    3. Now click on Relation view , here you can drop your foreign key constraint. You will get all relation here.
    0 讨论(0)
  • 2020-11-30 19:01

    Some ORM's or frameworks use a different naming convention for foreign keys than the default FK_[parent table]_[referenced table]_[referencing field], because they can be altered.

    Laravel for example uses [parent table]_[referencing field]_foreign as naming convention. You can show the names of the foreign keys by using this query, as shown here:

    SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
    WHERE REFERENCED_TABLE_SCHEMA = '<database>' AND REFERENCED_TABLE_NAME = '<table>';
    

    Then remove the foreign key by running the before mentioned DROP FOREIGN KEY query and its proper name.

    0 讨论(0)
  • 2020-11-30 19:03

    The simplest way to remove constraint is to use syntax ALTER TABLE tbl_name DROP CONSTRAINT symbol; introduced in MySQL 8.0.19:

    As of MySQL 8.0.19, ALTER TABLE permits more general (and SQL standard) syntax for dropping and altering existing constraints of any type, where the constraint type is determined from the constraint name

    ALTER TABLE tbl_magazine_issue DROP CONSTRAINT FK_tbl_magazine_issue_mst_users;
    

    db<>fiddle demo

    0 讨论(0)
  • 2020-11-30 19:04

    For those that come here using MariaDB:

    Note that MariaDB allows DROP CONSTRAINT statements in general, for example for dropping check constraints:

    ALTER TABLE table_name
    DROP CONSTRAINT constraint_name;
    

    https://mariadb.com/kb/en/library/alter-table/

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