不能在mysql中添加外键? [英] can't add foreign key in mysql?

查看:163
本文介绍了不能在mysql中添加外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MySQL工作台在表中添加外键,但是发生了一些奇怪的错误,这是SQL语句:

 <$ c $ ($)$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$' b参考`tansung`.`Goods`(`goodsId`)
在删除不作为
在更新不作为
,ADD INDEX`goodsId`(`goodsId` ASC);

当我点击应用时,惊喜就出来了!

 错误1005:无法创建表'tansung。#sql-1b10_1'(errno:150)

SQL语句:

ALTER TABLE`tansung`.`Declaration` ADD COLUMN`goodsId` INT(11)NOT NULL AFTER`declarationId`,
ADD CONSTRAINT`goodsId`
FOREIGN KEY(`goodsId`)
REFERENCES`tansung`.`Goods`(`goodsId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
,ADD INDEX`goodsId`(`goodsId` ASC)


错误:运行故障恢复脚本时出错。详情如下。


错误1050:表'Declaration'已经存在

SQL语句:

CREATE TABLE`Declaration`(
`declareId` int(11)NOT NULL,
PRIMARY KEY(`declarationId`)
)ENGINE = InnoDB DEFAULT CHARSET = utf8



我找不到任何逻辑错误,甚至不能理解错误,请给我一个帮助。

解决方案

整个数据库中的所有外键名称必须是唯一的。如果您已经有了一个名为'goodsId'的外键,即使在另一个表上,您也会收到这个错误消息。

如果相关列没有完全相同的类型例如INT)和约束(UNIQUE等),您将收到该错误。


I used MySQL workbench to add a foreign key in a table, but some strange error happened, this is the SQL statement:

ALTER TABLE `tansung`.`Declaration` ADD COLUMN `goodsId` INT(11) NOT NULL  AFTER `declarationId` , 
    ADD CONSTRAINT `goodsId`
        FOREIGN KEY (`goodsId` )
        REFERENCES `tansung`.`Goods` (`goodsId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION
    , ADD INDEX `goodsId` (`goodsId` ASC) ;

When i click apply, the surprise comes out!

ERROR 1005: Can't create table 'tansung.#sql-1b10_1' (errno: 150)

SQL Statement:

ALTER TABLE `tansung`.`Declaration` ADD COLUMN `goodsId` INT(11) NOT NULL  AFTER `declarationId` , 
    ADD CONSTRAINT `goodsId`
        FOREIGN KEY (`goodsId` )
        REFERENCES `tansung`.`Goods` (`goodsId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION
    , ADD INDEX `goodsId` (`goodsId` ASC)


ERROR: Error when running failback script. Details follow.


ERROR 1050: Table 'Declaration' already exists

SQL Statement:

CREATE TABLE `Declaration` (
    `declarationId` int(11) NOT NULL,
    PRIMARY KEY (`declarationId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

I can't find out any mistake in logic, even can't understand the error, please give me a help.

解决方案

All foreign key names throughout the database must be unique. If you already have a foreign key named 'goodsId', even on another table, you will receive this error.

If the related columns do not have exactly the same type (e.g. INT) and constraints (UNIQUE and such), you will receive that error.

这篇关于不能在mysql中添加外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆