Frage

I am using 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.

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:

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)
War es hilfreich?

Lösung 3

before adding any constrain to a table that already have some data might cause this problem,try to add constrain with out data

Andere Tipps

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.

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.

Error 121: This error explicitly is thrown when there is a duplication in key names.

Immediately after running your Alter ... statement, execute the following and observe the results.

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.

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.

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top