简体   繁体   English

添加外键时出错

[英]Error while adding Foreign key

I am using Mysql Workbench. 我正在使用Mysql Workbench。 I have already made the table. 我已经摆好桌子了。 Now I want to add foreign key in a table called Personal_Details that key is primary key in Login table. 现在,我想在名为Personal_Details的表中添加外键,该键是Login表中的主键。

But when I am trying to do so, it shows me the following error: 但是,当我尝试这样做时,它显示了以下错误:

ERROR 1005: Can't create table 'shaadiDB.#sql-404_25' (errno: 121)

SQL Statement: SQL语句:

ALTER TABLE `shaadiDB`.`Personal_Details` 
  ADD CONSTRAINT `Login_Id`
  FOREIGN KEY (`Login_Id` )
  REFERENCES `shaadiDB`.`Login` (`Login_Id` )
  ON DELETE NO ACTION
  ON UPDATE NO ACTION
, ADD INDEX `Login_Id` (`Login_Id` ASC)

It seems that the table Personal_Details is having data from which there might be some rows with Login_Id for which entry is not present in table Login . 似乎表Personal_Details包含的数据可能包含一些带有Login_Id的行,而该行的条目不在表Login

If this is the case , then solution would be that you need to move the data to another table, then add constraint. 如果是这种情况,那么解决方案是您需要将数据移动到另一个表,然后添加约束。 After adding the constraint you need to add all rows back to table 1 by 1. 添加约束后,您需要将所有行加回表1。

Error 121 : This error explicitly is thrown when there is a duplication in key names. 错误121 :如果键名重复,则会显式引发此错误。

Immediately after running your Alter ... statement, execute the following and observe the results. 在运行Alter ...语句后,立即执行以下命令并观察结果。

SHOW ENGINE InnoDB STATUS;

Description text from the result will tell you on which key name the duplication is found. 结果的描述文本将告诉您在哪个关键字名称上找到重复项。 Based on that you modify your ALTER ... statement and execute. 基于此,您可以修改ALTER ...语句并执行。

Alternatively you can also find if any such duplicate key name is defined by executing: 另外,您还可以通过执行以下命令查找是否定义了任何重复的键名:

select constraint_name, constraint_type, table_name
from information_schema.table_constraints
where table_schema = DATABASE() -- and constraint_type = 'foreign key'

Constraint types can be anything like PRIMARY KEY , FOREIGN KEY , etc. 约束类型可以是PRIMARY KEYFOREIGN KEY等。

If you see any key names in the result that you are trying to use in your ALTER .. statement, you should modify them and execute. 如果您在尝试在ALTER ..语句中使用的结果中看到任何键名,则应该对其进行修改并执行。

在将任何约束添加到已经有一些数据的表之前,可能会导致此问题,请尝试添加没有数据的约束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM