Search code examples
mysqlforeign-keysindexingalter-tablemysql-error-1005

MYSQL alter table - add INDEX + FOREIGN KEY give error 1005


what is wrong with this alter table command :

ALTER TABLE `lp` 
ADD COLUMN `RuleId` INT(10) NOT NULL DEFAULT -111 AFTER `Weight` , , 
ADD CONSTRAINT `fk_1` FOREIGN KEY (`RuleId` ) REFERENCES `Rules` (`RuleId` ) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD INDEX `fk_1` (`RuleId` ASC) ;

if i drop the line

  ADD CONSTRAINT `fk_1` FOREIGN KEY (`RuleId` ) REFERENCES `Rules` (`RuleId` ) ON DELETE NO ...

its work ,

the error i get is :

Error Code : 1005
Can't create table '..' (errno: 121)

how can i add a FOREIGN KEY and INDEX on the same field ?

Update:

i try to separate to 2 queries, first add INDEX and after that add FOREIGN KEY, the index added but the second query do not work !

when i change the name of foreign key (like : 'fk_2') and try run it i get an error : Error Code : 1452 Cannot add or update a child row: a foreign key constraint fails


Solution

  • First create the index and second the foreign key constraint. MySQL needs an index to create the foreign key, that's why you have to create the index first. Use seperate statements as well.