Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropping a column with a foreign key

On my mysql DB with inno_db engine,

I have a table with a foreign key. I want to drop the column (along with the foreign key and the associated index of course - i don't need the whole column!)

Now, simply dropping it yields an error: General error: 1025 Error on rename of '.\road_dmy#sql-19d8_2be' to '.\road_dmy\contact' (errno: 150)

It sounds like this is a known issue. http://bugs.mysql.com/bug.php?id=15317

But anyway, what should i do to drop this column? I'm very sure it's possible nobody would use this DB otherwise

(and b.t.w. how can I know the true details of the mysterious error message above?)

like image 587
shealtiel Avatar asked Apr 08 '11 01:04

shealtiel


People also ask

Can we drop a table with foreign key?

In SQL Server, you cannot drop a table if it is referenced by a FOREIGN KEY constraint. You have to either drop the child tables before removing the parent table, or remove foreign key constraints.

What happens to a foreign key when a table is dropped?

More commonly, dangling foreign keys crop up when you remove a table or column that was being referenced elsewhere in the database.

Does dropping a table drop foreign key constraint?

By default, when a primary/unique key is dropped, all foreign keys referencing the key being dropped are also dropped, unless the RESTRICT drop option is specified. Constraints are also dropped when the associated tables/schemas/databases are dropped. The DROP commands support the CASCADE | RESTRICT drop options.


1 Answers

You must drop the key first. I don't know the names of your tables but I'll give you the general strategy by example. Suppose you have the following 2 InnoDB tables:

CREATE TABLE `A` (
   `id` int(10) unsigned NOT NULL auto_increment,
    PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

CREATE TABLE `B` (
    `id` int(10) unsigned NOT NULL auto_increment,
    `a_id` int(10) unsigned NOT NULL,
    PRIMARY KEY  (`id`),
    KEY `a_id` (`a_id`),
    CONSTRAINT `b_ibfk_1` FOREIGN KEY (`a_id`) REFERENCES `a` (`id`)
) ENGINE=InnoDB;

You can drop the a_id column in table B using the following command:

alter table B drop foreign key b_ibfk_1, drop column a_id;
like image 194
Asaph Avatar answered Oct 01 '22 13:10

Asaph