Reputation: 1752
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?
Upvotes: 2
Views: 3806
Reputation: 5846
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`;
Upvotes: 4