0

我正在尝试在 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;
4

1 回答 1

1

在这里,我已经解决了您的问题并为我工作得很好

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

首先我改变QuestionIdprimary 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希望它也适合你

于 2012-09-30T05:40:52.450 回答