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,问题解决

猜你喜欢

转载自blog.csdn.net/miss_audrey/article/details/80681284