简体   繁体   中英

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

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.

I had the same problem exactly.

What I've found is that you can't add a foreign key if there already exists another foreign key in your database that has the exact same name. Even if that other foreign key is on a different table .

ERROR 1005 (HY000): Can't create table './MyDB/#sql-e4a_c715.frm' (errno: 121) As mentioned above, you will get this message if you're trying to add a constraint with a name that's already used somewhere else.

(Taken from here )

So just rename it to something random to check if I'm correct..

I got this error after combining schema DDLs from N Django apps using the "manage.py sqlall" command.

I found that MySQL's DDL requires the statements be grouped by kind in this order. Specifically, all ALTER TABLE ... ADD ... FOREIGN KEY ... must occur last, or MySQL will raise that error.

  1. CREATE TABLE ...
  2. CREATE INDEX ...
  3. ALTER TABLE table_name ADD CONSTRAINT name FOREIGN KEY ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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