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

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

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面