似乎添加包含外键的复合唯一键会破坏表:无法删除唯一键:
drop index test_unq on order_test
错误:
Cannot drop index 'test_unq': needed in a foreign key constraint
重现的步骤:
create table product_test (
id bigint unsigned not null auto_increment primary key
);
create table order_test (
id bigint unsigned not null auto_increment primary key,
product_id bigint unsigned not null,
foreign key (product_id) references product_test(id)
);
alter table order_test add some_field int not null;
alter table order_test add unique test_unq(product_id, some_field);
正在运行
SHOW CREATE TABLE order_test
返回
CREATE TABLE `order_test` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`product_id` bigint(20) unsigned NOT NULL,
`some_field` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `test_unq` (`product_id`,`some_field`),
CONSTRAINT `order_test_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES
`product_test` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
结果看起来无效,有一个约束但没有product_id的键。
有关如何恢复表而不删除并再次创建它的任何想法?
谢谢!
编辑:
删除所有其他外键无济于事!删除后的结构:
CREATE TABLE `order_test` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`product_id` bigint(20) unsigned NOT NULL,
`some_field` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `test_unq` (`product_id`,`some_field`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
当我尝试删除索引时出现相同的错误。
drop index test_unq on order_test
错误:
Cannot drop index 'test_unq': needed in a foreign key constraint