删除muli-column唯一键而不删除外键? [英] Drop muli-column unique key without dropping foreign key?

查看:63
本文介绍了删除muli-column唯一键而不删除外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从也有外键的表中删除多列唯一键.除非先删除外键,否则我一直得到"errno 150".

I am trying to delete a multi-column unique key from a table that also has a foreign key. I keep getting 'errno 150', unless I delete the foreign key first.

例如,如果我创建表:

CREATE TABLE `testtable` (
    `testtable_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `testtable_value` char(255) DEFAULT NULL,
    `othertable_id` int(10) unsigned NOT NULL,
    PRIMARY KEY (`testtable_id`),
    UNIQUE KEY `tt_unique_key` (`othertable_id`,`testtable_value`),
    CONSTRAINT `tt_foreign_key` FOREIGN KEY (`othertable_id`) REFERENCES `othertable` (`othertable_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

然后我尝试删除唯一键,如下所示:

and I try to remove the unique key like this:

ALTER TABLE `testtable` DROP KEY `tt_unique_key`;

它生成错误:

Error Code: 1025
Error on rename of './testdb/#sql-374_27' to './testdb/testtable' (errno: 150)

我尝试将FOREIGN_KEY_CHECKS设置为0,但出现相同的错误:

I tried setting FOREIGN_KEY_CHECKS = 0, but I get the same error:

SET FOREIGN_KEY_CHECKS = 0;
ALTER TABLE `testtable` DROP KEY `tt_unique_key`;
SET FOREIGN_KEY_CHECKS = 1;

这会产生与上面相同的错误消息.

This generates the same error message as above.

但是,如果我先删除外键,然后删除唯一键,然后重新创建外键,则一切正常:

However, if I first delete the foreign key, then delete the unique key, then recreate the foreign key, everything works:

ALTER TABLE `testtable` DROP FOREIGN KEY `tt_foreign_key`;
ALTER TABLE `testtable` DROP KEY `tt_unique_key`;
ALTER TABLE `testtable` ADD CONSTRAINT `tt_foreign_key` FOREIGN KEY (`othertable_id`) REFERENCES `othertable` (`othertable_id`);

这似乎效率很低.谁能解释这是怎么回事?有没有一种方法可以先删除唯一键而不先删除外键?

This seems really inefficient. Can anyone explain what is going on? Is there a way to drop the unique key without dropping the foreign key first?

推荐答案

一个外键引用,需要一个键,
唯一可以使用的密钥是t_unique_key, 这就是为什么您无法删除它的原因. 因此,请先添加另一个匹配的键,然后删除旧的键(在您的情况下为othertable_id字段)

a FOREIGN KEY REFERENCES, require a key,
the only key that can be used is t_unique_key, thats why you can't remove it.
so add another matching key first, and then remove the old key, in your case the othertable_id field

ALTER TABLE `testtable`
ADD KEY (othertable_id),
DROP KEY `tt_unique_key`;

这篇关于删除muli-column唯一键而不删除外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆