当我们在一个表中添加字段约束的时候:
ALTER TABLE product ADD CONSTRAINT product_fk FOREIGN KEY(category_id) REFERENCES category(id);
会认为我的外键约束名称为product_fk, 然后当我们想删除时:
ALTER TABLE product DROP FOREIGN KEY product_fk;
会出现以下的错误:
<e>Query: alter table product drop foreign key product_fk
Error Code: 1025
Error on rename of '.web_day09product' to '.web_day09#sql2-2330-1' (errno: 152)
这是因为字段的外键约束名并不是product_fk 。我们在数据库中执行一下命令:
SHOW CREATE TABLE product
控制台会显示
Table Create Table product
CREATE TABLE `product` (
`pid` varchar(32) NOT NULL,
`pname` varchar(40) DEFAULT NULL,
`price` double DEFAULT NULL,
`category_id` varchar(32) DEFAULT NULL,
PRIMARY KEY (`pid`),
KEY `category_id` (`category_id`),
CONSTRAINT `product_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `category` (`cid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
从建表语句中我们发现外键约束名称是:
product_ibfk_1
然后我们再执行外键删除操作
alter table product drop foreign key product_ibfk_1
0 row(s) affected
原文出处:https://blog.csdn.net/qq_35604488/article/details/90573415