开发者

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 ACTIO开发者_开发知识库N 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 ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜