【发布时间】:2019-12-02 14:48:24
【问题描述】:
我必须创建一个数据库,这是 MySQL 代码:
drop database if EXISTS BibliotecaLello;
create database BibliotecaLello;
use BibliotecaLello;
create table Lettore
(
CodiceFiscale varchar(17) PRIMARY KEY not null
);
create TABLE Tessera
(
CodiceLettore varchar(17),
CodiceTessera integer PRIMARY KEY not null AUTO_INCREMENT,
Nome varchar(10) not null,
Cognome varchar(10) not null,
unique(Nome, Cognome)
);
create table Autori
(
IDAutore integer PRIMARY KEY NOT null AUTO_INCREMENT,
Nome varchar(20) not null,
Cognome varchar(20) not null
);
create table Libro
(
CodiceLibro integer AUTO_INCREMENT PRIMARY KEY not null,
IDAutore integer not null,
Titolo varchar(20) not null
);
create table Copia
(
CodiceLibro integer not null,
CodiceCopia integer not null,
unique(CodiceLibro, CodiceCopia)
);
create table Noleggio
(
CodiceLettore varchar(17) not null,
DataInizio date not null,
DataFine date not null,
CodiceLibro integer not null,
CodiceCopia integer not null,
unique(CodiceLettore, DataInizio, DataFine, CodiceLibro, CodiceCopia)
);
alter table Noleggio add CONSTRAINT fkNolleggioLettore
FOREIGN key (CodiceLettore)
REFERENCES `Lettore`(`CodiceFiscale`) on DELETE CASCADE on UPDATE CASCADE;
alter table Tessera add CONSTRAINT fkTesseraLettori
FOREIGN KEY (`CodiceLettore`)
REFERENCES `Lettore`(`CodiceFiscale`) on DELETE CASCADE on UPDATE cascade;
alter table Libro add CONSTRAINT fkLibroAutori
FOREIGN KEY (IDAutore)
REFERENCES `Autori`(`IDAutore`) on DELETE CASCADE on UPDATE cascade;
alter table `Copia` add CONSTRAINT fkCopieLibro
FOREIGN KEY (CodiceLibro)
REFERENCES Libro(CodiceLibro) on DELETE CASCADE on UPDATE cascade;
alter table Noleggio add CONSTRAINT fkNoleggioCopiaCopia
FOREIGN KEY (CodiceCopia)
REFERENCES `Copia`(`CodiceCopia`) on DELETE CASCADE on UPDATE cascade;
alter table Noleggio add CONSTRAINT fkNoleggioCopiaLibro
FOREIGN KEY (CodiceLibro)
REFERENCES `Copia`(`CodiceLibro`) on DELETE CASCADE on UPDATE cascade;
但是当我执行时
alter table Noleggio add CONSTRAINT fkNoleggioCopiaCopia
FOREIGN KEY (CodiceCopia)
REFERENCES `Copia`(`CodiceCopia`) on DELETE CASCADE on UPDATE cascade;
我明白了
ERROR 1005 (HY000): Can't create table `BibliotecaLello`.`#sql-2f7_2c2` (errno: 150 "Foreign key constraint is incorrectly formed")
我试过了
SHOW ENGINE INNODB STATUS
这是LATEST FOREIGN KEY ERROR
的结果2019-12-02 14:37:25 75ea2340 Error in foreign key constraint of table `BibliotecaLello`.`Noleggio`:
FOREIGN KEY (CodiceCopia)
REFERENCES `Copia`(`CodiceCopia`) on DELETE CASCADE on UPDATE cascade:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
我的老师告诉我,这意味着我正在更改错误的表格,但尝试使用两个表格仍然无法正常工作。 你能帮我解决这个问题吗?
【问题讨论】:
标签: mysql sql database foreign-keys create-table