26

我想在我的表中删除外键但进入此错误消息

mysql> alter table customers drop foreign key customerid;
ERROR 1025 (HY000): Error on rename of '.\products\customers' to '.\products\#sql2-7ec-a3' (errno: 152)
mysql>
4

5 回答 5

34

The solution described here by Chris White worked for me.

The root problem is that MySQL creates both an index and a foreign key. Both must be removed (the foreign key first contrary to what Chris said).

  1. show create table table_name;

    SHOW CREATE TABLE `table_name`:
    
    | table_name | CREATE TABLE `table_name` (
      `id` int(20) unsigned NOT NULL auto_increment,
      `key_column` smallint(5) unsigned default '1',
      KEY `column_tablein_26440ee6` (`key_column`),  <--- shows key name
      CONSTRAINT `table_name_ibfk_1` FOREIGN KEY (`key_column`) REFERENCES <--- shows foreign key constraint name
    `second_table` (`id`) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
    
  2. Delete the foreign key constraint:

    ALTER TABLE table_name DROP FOREIGN KEY `table_name_ibfk_1`;
    
  3. Delete the key

    ALTER TABLE table_name DROP KEY `column_tablein_26440ee6`;
    

That did it for me.

于 2014-02-04T21:18:46.193 回答
7

它看起来像 MySQL 的错误消息中的一个错误。( http://bugs.mysql.com/bug.php?id=10333 )

使用 SHOW CREATE TABLEtable_name查看外键的实际名称。生成外键名称拼写错误的查询时,看起来可能是 mysql 查询浏览器问题。

于 2012-05-17T09:04:32.980 回答
6

为避免在尝试删除外键时出现此错误,请使用约束名称而不是外键的列名。

当我尝试

mysql> ALTER TABLE mytable DROP PRIMARY KEY;

我得到了错误

ERROR 1025 (HY000): Error on rename of '.\database\#sql-454_3' to '.\database\mytable' (errno: 150).

我使用以下方法解决了它:

mysql> ALTER TABLE mytable DROP PRIMARY KEY, ADD PRIMARY KEY (column1,column2,column3);

一些对您有帮助的链接。

链接 1

link 2 [look for Posted by Alex Blume on November 7 2008 5:09pm & Posted by Hector Delgadillo on January 21 2011 4:57am]

于 2012-05-17T09:34:36.990 回答
1

为避免在尝试删除外键时出现此错误,请使用约束名称而不是外键的列名称

于 2012-05-17T09:02:54.930 回答
0

You should try with the foreign key name as Fahim Parkar suggested. Actually that does not work always either.

In my case I used the

FOREIGN KEY `fk`(`col1`) REFERENCES `table2`(`col1`)

code to add the fk by creation.

The problem with this code that it is not valid and should throw some kind of syntax error, but still it added a foreign key with a random name.

When I added the fk with the right syntax:

CONSTRAINT `fk` FOREIGN KEY (`col1`) REFERENCES `table2`(`col1`)

the following code dropped it properly:

ALTER TABLE `table1` DROP FOREIGN KEY `fk`

So this kind of error can happen too if you try to remove a foreign key with an invalid name. It is important to view the table properties with

SHOW CREATE TABLE `table1`

and check the foreign key names if you get this kind of errors.

于 2017-03-07T05:20:29.900 回答