尝试添加多个外键时,sql中出现错误

时间:2012-09-29 22:44:09

标签: mysql sql database

我正在尝试在mysql中创建一个索引和多个外键但是当我包含下面的代码时:

CREATE INDEX par_ind on Image_Question (SessionId,QuestionId);

ALTER TABLE Image_Question ADD CONSTRAINT FK_CONSTRAINT_NAME
                           FOREIGN KEY (SessionId,QuestionId) 
                             REFERENCES Question(SessionId,QuestionId)
                             ON DELETE CASCADE;

创建索引工作正常,但它不允许我更改表并添加外键。我给了我一个错误说明:

#1452 - Cannot add or update a child row: a foreign key constraint fails (`mobile_app`.<result 2 when explaining filename '#sql-4517_14f1a'>, CONSTRAINT `FK_CONSTRAINT_NAME` FOREIGN KEY (`SessionId`, `QuestionId`) REFERENCES `Question` (`SessionId`, `QuestionId`) ON)

此错误的含义是什么?如何排除此错误?

下面是Image_Question表:

CREATE TABLE Image_Question (ImageQuestionId INT     NOT NULL, 
                             ImageId          INT     NOT NULL,
                             SessionId        CHAR(3) NOT NULL,
                             QuestionId       INT     NOT NULL,
                            PRIMARY KEY (ImageQuestionId)
                            ) ENGINE=INNODB;

下面是问题表:

CREATE TABLE Question (QuestionId INT      NOT NULL, 
                       SessionId  CHAR(3)  NOT NULL,
                       Question   CHAR(10) NOT NULL ) ENGINE=INNODB;

1 个答案:

答案 0 :(得分:1)

在这里,我已经解决了你的问题并为我工作正常

ALTER TABLE `question`     CHANGE `QuestionId` `QuestionId` INT(11) NOT NULL,    ADD PRIMARY KEY(`QuestionId`);

首先我将QuestionId更改为primary key

ALTER TABLE `image_question` ADD INDEX `questionId` (`QuestionId`);

然后在QuestionId

image_question添加了索引
ALTER TABLE  `question` ADD CONSTRAINT `FK_question` FOREIGN KEY (`QuestionId`)
REFERENCES `image_question` (`QuestionId`) ON DELETE NO ACTION ;

然后QuestionId的第一个关系成功运作

ALTER TABLE `question`     CHANGE `SessionId` `SessionId` INT(11) NOT NULL;
ALTER TABLE `image_question`     CHANGE `SessionId` `SessionId` INT(11) NOT NULL;

然后将两个表的SessionId的数据类型更改为int

ALTER TABLE `image_question` ADD INDEX `NewIndex1` (`SessionId`);

然后在SessionId

image_question添加了索引
ALTER TABLE `image_question` ADD CONSTRAINT `FK_image_question` FOREIGN KEY (`SessionId`) REFERENCES `question` (`SessionId`) ON DELETE NO ACTION ;

这是你SessionId的第二个关系,希望它也适合你