MySQL删除外键错误152

时间:2012-07-25 11:54:49

标签: mysql foreign-keys alter-table

我试图使用以下方法删除一些外键:

ALTER TABLE `table` DROP FOREIGN KEY `fk_table_users1` , DROP FOREIGN KEY `fk_table_accounts1` , DROP FOREIGN KEY `fk_table_data1` ;

但它返回错误:

Error on rename of './db/table' to './db/#sql2-179c-288289' (errno: 152)

我已经运行了SHOW ENGINE INNODB STATUS,其中说:

120725 12:38:37 Error in dropping of a foreign key constraint of table db/table,
in SQL command
ALTER TABLE `table` DROP FOREIGN KEY `fk_table_users1` , DROP FOREIGN KEY `fk_table_accounts1` , DROP FOREIGN KEY `fk_table_data1` 
Cannot find a constraint with the given id fk_table_users1.

SHOW CREATE TABLE 'table'输出:

CREATE TABLE `table` (
 `id` int(11) NOT NULL auto_increment,
 `data_id` int(11) NOT NULL,
 `account_id` int(11) NOT NULL,
 `status` enum('pending','complete') NOT NULL default 'pending',
 `created_at` datetime NOT NULL,
 `created_by` int(11) NOT NULL,
 PRIMARY KEY  (`id`),
 KEY `fk_orders_users1` (`created_by`),
 KEY `fk_orders_data1` (`data_id`),
 KEY `fk_orders_accounts1` (`account_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

然而,当我通过phpmyadmin查看结构时,它列出了具有相同名称的外键。在丢弃外键之前,我是否需要做其他事情?

4 个答案:

答案 0 :(得分:10)

没有外键。请参阅说明

MySQL documentation
KEY is normally a synonym for INDEX.

所以基本上在表中你创建了索引,而不是外键。 For Foreign Key info, Click here

答案 1 :(得分:2)

您需要暂时删除约束,以便将其删除。

SET FOREIGN_KEY_CHECKS = 0;

然后在删除外键后再次打开它们:

SET FOREIGN_KEY_CHECKS = 1;

答案 2 :(得分:0)

首先删除外键然后删除列

alter table'table name'drop foreign key'constitution id;

如果你不知道约束id创建数据库转储,那么约束id在转储文件中可用..

然后删除列..

答案 3 :(得分:0)

索引名称和约束名称可能不相同。您应该首先使用代码删除约束:ALTER TABLE tablename DROP FOREIGN KEY constraintname