简体   繁体   中英

MySQL can't create table with foreign key

CREATE  TABLE `assessmentbookdb`.`MCQs` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `MCQAnswer` VARCHAR(200) NOT NULL ,
  `QuestionID` INT NOT NULL ,
  PRIMARY KEY (`id`) ,
  INDEX `QuestionID` (`QuestionID` ASC) ,
  CONSTRAINT `QuestionID`
    FOREIGN KEY (`QuestionID` )
    REFERENCES `assessmentbookdb`.`Question` (`QuestionID` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

Message Log:

ERROR 1005: Can't create table 'assessmentbookdb.mcqs' (errno: 121) SQL Statement:

CREATE  TABLE `assessmentbookdb`.`MCQs` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `MCQAnswer` VARCHAR(200) NOT NULL ,
  `QuestionID` INT NOT NULL ,
  PRIMARY KEY (`id`) ,
  INDEX `QuestionID` (`QuestionID` ASC) ,
  CONSTRAINT `QuestionID`
    FOREIGN KEY (`QuestionID` )
    REFERENCES `assessmentbookdb`.`Question` (`QuestionID` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
    ENGINE = InnoDB

Double-check that:

  • The key's name is unique
  • The two keys you're coupling have the exact same datatype (here: INT NOT NULL ), even signedness
  • The referencing fields actually exist

based on googling i would assume that you have a constraint that exists with the same name that you try to add a constraint with. It might be that you didnt delete an old constraint from the old version of the table or something.

table creation failed because a foreign key constraint was not correctly formed

Somehow your foreign key is not correct. This can be if the table you are refering does not exist yet.

在这里看看,并尝试不给您的约束起一个名字。

http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

InnoDB supports foreign keys, which let you cross-reference related data across tables, and foreign key constraints, which help keep this spread-out data consistent. The syntax for an InnoDB foreign key constraint definition in the CREATE TABLE or ALTER TABLE statement looks like this:

 [CONSTRAINT [symbol]] FOREIGN KEY
 [index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]

 reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION

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