我将实现一个书店数据库。我创建了表book,author和publisher。我想建立以下两个关系。
book
author
publisher
Book is written by Author. Book is published by Publisher.
为了实现这些关系,我编写了一些SQL语句,例如:
create table book( ISBN varchar(30) NOT NULL, title varchar(30) not null, author varchar(30) not null, stock Int, price Int, category varchar(30), PRIMARY KEY ( ISBN ) ); create table author( author_id int not null auto_increment, author_name varchar(15) NOT NULL, address varchar(50) not null, ISBN varchar(30) not null, primary key (author_id) ); alter table author add constraint ISBN foreign key (ISBN) references book (ISBN); create table publisher( publisher_id int not null auto_increment, publisher_name varchar(15) NOT NULL, address varchar(50) not null, ISBN varchar(30) not null, primary key (publisher_id) ); alter table publisher add constraint ISBN foreign key (ISBN) references book (ISBN);
当MySQL Shell执行最后一条alter语句时,出现此错误。
alter
ERROR 1022 (23000): Can't write; duplicate key in table '#sql-2b8_2'
本来不能指定两次外键?怎么了 先感谢您。
您正在得到duplicate keyerror原因,因为ISBN您alter对author表的第一条语句已经在数据库中存在一个名为约束的约束
duplicate keyerror
ISBN
alter table author add constraint ISBN foreign key (ISBN) references book (ISBN);
尝试对Publisher表中的约束使用其他名称
Publisher
alter table publisher add constraint ISBN1 foreign key (ISBN) references book (ISBN);