Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

mysql - Drop muli-column unique key without dropping foreign key?

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.

For example, if I create the table:

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`;

It generates the error:

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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`;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
...