mysql删除unique 报错: MySQL Cannot drop index needed in a foreign key constraint

创建好了class表

create table class (
    cid int not null unique auto_increment,
    caption varchar(20) not null,
    grade_id int not null unique,
    foreign key (grade_id) references class_grade(gid)
    );

然而,发现grade_id 并不能设置为唯一键,只好把它给删掉,可是删除尝试了很多种办法,老是报错,最后中找到解决办法,就是这个错误导致的 MySQL Cannot drop index needed in a foreign key constraint
因为这个字段我已经关联了外键,要先把外键去除才能删掉这个unique(不要忘记删除完了再关联回来)

删除外键

ALTER TABLE <Table Name> DROP FOREIGN KEY <Foreign key name>
ALTER TABLE class DROP FOREIGN KEY class_ibfk_1 ;

如果没有设置约束名,可以用此查询语句(mysql会设置为默认的约束名)

show create table <Table Name>
show create table class\G;
*************************** 1. row ***************************
       Table: class
Create Table: CREATE TABLE `class` (
  `cid` int(11) NOT NULL AUTO_INCREMENT,
  `caption` varchar(20) NOT NULL,
  `grade_id` int(11) NOT NULL,
  UNIQUE KEY `cid` (`cid`),
  UNIQUE KEY `grade_id_2` (`grade_id`),
  CONSTRAINT `class_ibfk_1` FOREIGN KEY (`grade_id`) REFERENCES `class_grade` (`gid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR:
No query specified

删除unique

alter table class drop index grade_id_2;

最后把删除的约束加上

 alter table class 
 add constraint `class_ibfk_1` FOREIGN KEY (`grade_id`) REFERENCES `class_grade` (`gid`) 
on update cascade;

ok,问题解决

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值