MySQL刪除外鍵定義的方法
MySQL外鍵在定以后,如果我們不再需要這個(gè)外鍵,可以進(jìn)行刪除操作,下面就為您介紹MySQL刪除外鍵定義的方法,供您參考。
不知道大家有沒有發(fā)現(xiàn),在定義外鍵的時(shí)候articles.member_id外鍵比articles.category_id子句多了一個(gè)CONSTRAINT fk_member ?
這個(gè)fk_member就是用來實(shí)現(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外鍵定義就被刪除了,但是如果定義時(shí)沒有指定CONSTRAINT fk_symbol (即外鍵符號(hào))時(shí)該怎么實(shí)現(xiàn)MySQL刪除外鍵呢?別急,沒有指定時(shí),MySQL會(huì)自己創(chuàng)建一個(gè),可以通過以下命令查看:
- 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的外鍵符號(hào)為articles_ibfk_1,因?yàn)榫涂梢詧?zhí)行以下命令實(shí)現(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
【編輯推薦】