MySQL刪除外鍵定義的方法
MySQL外鍵在定以后,如果我們不再需要這個外鍵,可以進行刪除操作,下面就為您介紹MySQL刪除外鍵定義的方法,供您參考。
不知道大家有沒有發(fā)現(xiàn),在定義外鍵的時候articles.member_id外鍵比articles.category_id子句多了一個CONSTRAINT fk_member ?
這個fk_member就是用來實現(xiàn)MySQL刪除外鍵用的,如下所示:
- mysql> ALTER TABLE articles DROP FOREIGN KEY fk_member;
- Query OK, 1 row affected (0.25 sec)
- Records: 1 Duplicates: 0 Warnings: 0
這樣articles.member_id外鍵定義就被刪除了,但是如果定義時沒有指定CONSTRAINT fk_symbol (即外鍵符號)時該怎么實現(xiàn)MySQL刪除外鍵呢?別急,沒有指定時,MySQL會自己創(chuàng)建一個,可以通過以下命令查看:
- mysql> SHOW CREATE TABLE articles;
- +———-+————————————+
- | Table | Create Table |
- +———-+————————————+
- | articles | CREATE TABLE `articles` (
- `article_id` int(11) unsigned NOT NULL auto_increment,
- `category_id` tinyint(3) unsigned NOT NULL,
- `member_id` int(11) unsigned NOT NULL,
- `title` varchar(255) NOT NULL,
- PRIMARY KEY (`article_id`),
- KEY `category_id` (`category_id`),
- KEY `member_id` (`member_id`),
- CONSTRAINT `articles_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
- +———-+————————————+
- 1 row in set (0.01 sec)
可以看出articles.category_id的外鍵符號為articles_ibfk_1,因為就可以執(zhí)行以下命令實現(xiàn)MySQL刪除外鍵定義:
- mysql> ALTER TABLE articles DROP FOREIGN KEY articles_ibfk_1;
- Query OK, 1 row affected (0.66 sec)
- Records: 1 Duplicates: 0 Warnings: 0
【編輯推薦】