mysql delete foreign key constraints

How to completely delete foreign key constraints

Today, I will do with the operation of modifying the table. Although it is not used much, it is still very useful when doing experiments by myself. For example, add and delete foreign keys.

Add foreign key

It is divided into two steps :

1. 添加相应列
ALTER TABLE goods 
ADD stuid INT;
2. 添加约束
ALTER TABLE goods 
ADD CONSTRAINT fk_stu_goo 
FOREIGN KEY(stuid)
REFERENCES stuinfo(id);
- 附加创建goods表的语句
DROP TABLE IF EXISTS goods;
CREATE TABLE IF NOT EXISTS goods(
 id INT PRIMARY KEY auto_increment,
 name VARCHAR(20) NOT NULL,
 price DOUBLE DEFAULT 0
);

Adding constraints is very simple, and deleting constraints is also divided into two steps.

Delete foreign key

as follows

1.删除外键约束
ALTER TABLE goods DROP FOREIGN KEY fk_stu_goo;
2.删除键值约束
ALTER TABLE goods DROP INDEX fk_stu_goo;

Note: Only performing step 1 does not seem to be successful, and the foreign key constraint is initially deleted. But there is also a key statement that is executed in addition to the foreign key statement.

实行1之后的表创建语句如下:可以看到有申明KEY `fk_stu_goo` (`stuid`)
CREATE TABLE `goods` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `price` double DEFAULT '0',
  `stuid` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_stu_goo` (`stuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

Execution ALTER TABLE goods DROP stuid;will fail at this time . Therefore, you need to perform 2 to delete the index index.

Reference link

  • https://blog.csdn.net/u012430402/article/details/80337486
  • https://blog.csdn.net/qq_35604488/article/details/90573415

Zhuang Zhouxiao dreams of butterflies, and Wang Dichun cares for the cuckoo. ——Li Shangyin

Guess you like

Origin blog.csdn.net/weixin_37627774/article/details/107541813