我在 Ubuntu 16.04 LTS 上使用 Navicat 时遇到了问题,我正在尝试执行脚本,它在最后一个表上坏了,说无法添加外键约束,这是我的脚本,有人知道我在某处错了吗?
感谢建议
这是我的SQL脚本:
CREATE TABLE `SMER` (
`Ssmer` INT(10) NOT NULL AUTO_INCREMENT,
`Nazivs` VARCHAR(255) NOT NULL,
PRIMARY KEY (`Ssmer`)
);
CREATE TABLE `Nastavnici` (
`Snast` INT(10) NOT NULL AUTO_INCREMENT,
`Imen` VARCHAR(255) NOT NULL,
PRIMARY KEY (`Snast`)
);
CREATE TABLE `PREDMETI` (
`SPRED` INT(10) NOT NULL AUTO_INCREMENT,
`NAZIVP` VARCHAR(255) NOT NULL,
PRIMARY KEY (`SPRED`)
);
CREATE TABLE `Studenti` (
`Indeks` INT(10) NOT NULL,
`Upisan` INT(10) NOT NULL,
`Imes` VARCHAR(255) NOT NULL,
`Mesto` VARCHAR(255),
`Datr` DATETIME NOT NULL,
`Ssmer` INT(10) NOT NULL,
PRIMARY KEY (`Indeks`, `Upisan`),
CONSTRAINT `FK_Studenti_Ssmer` FOREIGN KEY (`Ssmer`) REFERENCES `SMER` (`Ssmer`)
);
CREATE TABLE `USLOVNI` (
`Spred` INT(10) NOT NULL,
`UslPredmet` INT(10) NOT NULL,
PRIMARY KEY (`Spred`, `UslPredmet`),
CONSTRAINT `FK_Uslovni_Spred` FOREIGN KEY (`Spred`) REFERENCES `PREDMETI` (`SPRED`),
CONSTRAINT `FK_Uslovni_UslPredmet` FOREIGN KEY (`UslPredmet`) REFERENCES `PREDMETI` (`SPRED`)
);
CREATE TABLE `Planst` (
`Ssmer` INT(10) NOT NULL,
`Spred` INT(10) NOT NULL,
`Semestar` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`Ssmer`, `Spred`),
CONSTRAINT `FK_Planst_Ssmer` FOREIGN KEY (`Ssmer`) REFERENCES `SMER` (`Ssmer`),
CONSTRAINT `FK_Planst_Spred` FOREIGN KEY (`Spred`) REFERENCES `PREDMETI` (`SPRED`)
);
CREATE TABLE `Angazovanje` (
`Snast` INT(10) NOT NULL,
`Spred` INT(10) NOT NULL,
`Ssmer` INT(10) NOT NULL,
PRIMARY KEY (`Snast`, `Spred`, `Ssmer`),
CONSTRAINT `FK_Angazovanje_Snast` FOREIGN KEY (`Snast`) REFERENCES `Nastavnici` (`Snast`),
CONSTRAINT `FK_Angazovanje_Spred` FOREIGN KEY (`Spred`) REFERENCES `PREDMETI` (`SPRED`),
CONSTRAINT `FK_Angazovanje_Ssmer` FOREIGN KEY (`Ssmer`) REFERENCES `SMER` (`Ssmer`)
);
CREATE TABLE `Prijave` (
`Spred` INT(10) NOT NULL,
`Indeks` INT(10) NOT NULL,
`Upisan` INT(10) NOT NULL,
`Snast` INT(10) NOT NULL,
`Datump` DATETIME DEFAULT NOW(),
`Ocena` INT(2) NOT NULL,
PRIMARY KEY (`Spred`, `Indeks`, `Upisan`, `Datump`),
CONSTRAINT `FK_Prijave_Spred` FOREIGN KEY (`Spred`) REFERENCES `PREDMETI` (`SPRED`),
CONSTRAINT `FK_Prijave_Indeks` FOREIGN KEY (`Indeks`) REFERENCES `Studenti` (`Indeks`),
CONSTRAINT `FK_Prijave_Upisan` FOREIGN KEY (`Upisan`) REFERENCES `Studenti` (`Upisan`),
CONSTRAINT `FK_Prijave_Snast` FOREIGN KEY (`Snast`) REFERENCES `Nastavnici` (`Snast`)
);
以下是错误消息:
[Err] 1215 - Cannot add foreign key constraint
Prijave
表中有两个 FK 指向Studenti
表。MySQL在这方面玩得并不好。
试试这个
CONSTRAINT `FK_Prijave_Indeks` FOREIGN KEY (`Indeks`, `Upisan`)
REFERENCES `Studenti` (`Indeks`, `Upisan`),
取而代之。
CONSTRAINT `FK_Prijave_Indeks` FOREIGN KEY (`Indeks`) REFERENCES `Studenti` (`Indeks`), /* wrong !*/
CONSTRAINT `FK_Prijave_Upisan` FOREIGN KEY (`Upisan`) REFERENCES `Studenti` (`Upisan`),