我试图在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;
在这里,我已经解决了您的问题,并为我工作得很好
ALTER TABLE `question` CHANGE `QuestionId` `QuestionId` INT(11) NOT NULL, ADD PRIMARY KEY(`QuestionId`);
首先,我已经改变了QuestionId对primary key
QuestionId
primary key
ALTER TABLE `image_question` ADD INDEX `questionId` (`QuestionId`);
然后追加的索引上QuestionId的image_question
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
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希望它也对您有效