douan7601
2017-12-10 00:00
浏览 298
已采纳

插入记录时出错无法添加或更新子行:外键约束失败

I have created tables in MYSQL as follows

Author Table

CREATE TABLE `author` (
`AuthorId` varchar(25) NOT NULL,
`AuthorName` varchar(50) NOT NULL,
 PRIMARY KEY (`AuthorId`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1

Books Table

 CREATE TABLE `books` (
 `DocId` int(11) NOT NULL,
 `ISBN` varchar(13) NOT NULL,
 PRIMARY KEY (`DocId`),
 KEY `DocId` (`DocId`),
 CONSTRAINT `books_ibfk_1` FOREIGN KEY (`DocId`) REFERENCES `document` 
 (`DocId`)
 ON DELETE CASCADE ON UPDATE CASCADE
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1

Document Table

 CREATE TABLE `document` (
 `DocId` int(11) NOT NULL,
 `Title` varchar(50) NOT NULL,
 `PublishDate` date DEFAULT NULL,
 `AuthorId` varchar(10) DEFAULT NULL,
 `DocType` varchar(10) DEFAULT NULL,
 PRIMARY KEY (`DocId`),
 KEY `AuthorId` (`AuthorId`),    
 CONSTRAINT `document_ibfk_3` FOREIGN KEY (`AuthorId`) REFERENCES `author` 
 (`AuthorId`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1

I made a server for my PHP website on XAMPP and am using mysql but when I try inserting the values in Document table I get

error while inserting the recordsCannot add or update a child row: a foreign 
key constraint fails (`librarydb`.`document`, CONSTRAINT `document_ibfk_3` 
FOREIGN KEY (`AuthorId`) REFERENCES `author` (`AuthorId`))

How do I resolve this issue?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dqg2269 2017-12-10 00:11
    最佳回答

    Your linked fields author.AuthorId and document.AuthorId are not defined the same way.
    From the docs:

    Corresponding columns in the foreign key and the referenced key must have similar data types. The size and sign of integer types must be the same. The length of string types need not be the same.

    So make them both varchar(10) NOT NULL - or whatever you need.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题