【问题标题】:MySQL Drop foreign key Error 152MySQL删除外键错误152
【发布时间】:2012-07-23 20:19:37
【问题描述】:

我正在尝试使用以下方法删除一些外键:

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 查看结构时,它会列出具有相同名称的外键。在删除外键之前我需要做其他事情吗?

【问题讨论】:

  • 请发布SHOW CREATE TABLE `table`;的输出。
  • @eggyal 用输出编辑了我的帖子
  • 我没有看到 any 外键约束...
  • 感谢您指出这一点。我们使用迁移脚本,看起来它没有添加外键

标签: mysql foreign-keys alter-table


【解决方案1】:

没有外键。参考MySQL documentation,上面写着

KEY is normally a synonym for INDEX.

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

【讨论】:

  • 一个小但可能不错的问题:我遇到了这个问题。使用这个答案我仔细检查了自己并注意到我试图删除约束所需的 KEY 。 'drop' 语句中的一个小修复,将名称从键名更改为约束名 - 和 violla!
【解决方案2】:

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

SET FOREIGN_KEY_CHECKS=0;

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

SET FOREIGN_KEY_CHECKS=1;

【讨论】:

  • 你可能是指最后一行的=1 ;)
【解决方案3】:

先删除外键,再删除列

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

如果您不知道约束 id 创建数据库转储,则该约束 id 在转储文件中可用..

然后删除列..

【讨论】:

    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 2011-07-17
      • 2011-10-15
      • 2015-06-16
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      • 2010-10-24
      • 2012-01-10
      • 2015-02-22
      相关资源
      最近更新 更多