微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当我的外键索引与它所引用的表中的主键匹配时,为什么会出现错误代码:1822?

如何解决当我的外键索引与它所引用的表中的主键匹配时,为什么会出现错误代码:1822?

create table item
(
isbn varchar(25) not null,title varchar(150) not null,publisher_name varchar(50) not null,classification_code varchar(10) not null,format_type char(2),constraint item_pk primary key(isbn)
);

create table copy 
(
isbn varchar(25) not null,copy_id int not null,acquired_date not null,constraint copy_pk primary key(isbn,copy_id),constraint copy_fk foreign key(isbn) references item(isbn)
);

create table borrow (
isbn varchar(25) not null,user_id varchar(25) not null,borrowed_datetime datetime not null,returned_datetime datetime not null,constraint borrow_pk primary key (isbn,copy_id,user_id,borrowed_datetime),constraint borrow_fk_1 foreign key(isbn) references copy(isbn),constraint borrow_fk_2 foreign key(copy_id) references copy(copy_id),);

这是我来自 MysqL代码,每次我尝试运行它时,只会创建表项和副本。由于“错误代码:1822。未能添加外键约束。在引用的表‘copy’中缺少约束‘borrow_fk_2’的索引”,因此未创建表借用。

我的搜索引擎是 InnoDB。

解决方法

要引用复合主键,您必须声明一个与主键列数相同且顺序相同的外键。在您的情况下,您需要像这样的 (isbn,copy_id) 外键:

create table borrow (
isbn varchar(25) not null,copy_id int not null,user_id varchar(25) not null,borrowed_datetime datetime not null,returned_datetime datetime not null,constraint borrow_pk primary key (isbn,copy_id,user_id,borrowed_datetime),constraint borrow_fk_1 foreign key(isbn,copy_id) references copy(isbn,copy_id)
);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。