错误code:1215 cannot 在mysql workbench版本6.3中运行脚本时添加外键约束

brvekthn  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(295)

首先,我很抱歉,这些表的名称等都是用另一种语言写的。
问题是,出于某种原因,我似乎无法将kopia\u knihy表中名为id\u kopie的外键添加到sklad表中。当它将外键添加到表sklad时,抛出一个错误1215。代码如下:

CREATE TABLE BOOK (
    BOOK_NAME VARCHAR(30)     NOT NULL,
    YEAR      CHAR(4)         NOT NULL,
    NAME_OF_EDITOR   VARCHAR(30)     NOT NULL,    
    WRITER_ID INTEGER NOT NULL,
    ISBN        VARCHAR(17)     NOT NULL,
    BOOK_ID    INTEGER         NOT NULL,
    PRIMARY KEY (BOOK_ID),
);
CREATE TABLE BOOK_COPY(
    BOOK_ID INTEGER NOT NULL,
    LANGUAGE_CODE CHAR(3) NOT NULL,
    COPY_ID INTEGER NOT NULL,
    BOOK_PICTURES CHAR(1) NOT NULL 
        CHECK (BOOK_PICTURES IN ("Y", "N")),
    PRIMARY KEY (BOOK_ID, LANGUAGE_CODE, COPY_ID)
    FOREIGN KEY(BOOK_ID)
        REFERENCES BOOK(BOOK_ID),
);
CREATE TABLE STORAGE (
    BOOK_ID INTEGER NOT NULL,
    COPY_ID INTEGER NOT NULL,
    BUILDING_ID INTEGER NOT NULL,
    ROOM_NUMBER NUMERIC(4,0) NOT NULL,
    SHELF_NUMBER NUMERIC(4,0) NOT NULL,
    PRIMARY KEY(BOOK_ID, BUILDING_ID, COPY_ID),
    FOREIGN KEY(COPY_ID)
        REFERENCES BOOK_COPY(BOOK_ID),
)

我在网上查了一下错误代码1215,没有发现我的数据库有什么问题。我检查了一下是否有错别字或者我是否忘了添加参考资料。
这是错误:

0   769 18:19:37    CREATE TABLE STORAGE (
    BOOK_ID INTEGER NOT NULL,
    COPY_ID INTEGER NOT NULL,
    BUILDING_ID INTEGER NOT NULL,
    ROOM_NUMBER NUMERIC(4,0) NOT NULL,
    SHELF_NUMBER NUMERIC(4,0) NOT NULL,
    PRIMARY KEY(BOOK_ID, BUILDING_ID, COPY_ID),
    FOREIGN KEY(COPY_ID)
        REFERENCES BOOK_COPY(BOOK_ID),
)
Error Code: 1215. Cannot add foreign key constraint 0.016 sec

我的问题是,如何才能解决这个问题,它将工作。
我们将不胜感激。

ql3eal8s

ql3eal8s1#

这样试试。请一定要把这张表改一下 ON UPDATE ... ON DELETE 本例中的语法与您需要的语法相同。

CREATE TABLE `KNIHA` (
`NAZOV_KNIHY` VARCHAR(30)     NOT NULL,
`ROK_PRVEHO_VYDANIA` CHAR(4)         NOT NULL,
`NAZOV_VYDAVATELA`   VARCHAR(30)     NOT NULL,    
`ID_AUTORA` INTEGER NOT NULL,
`ISBN`        VARCHAR(17)     NOT NULL,
`ID_KNIHY`    INTEGER         NOT NULL,
PRIMARY KEY (`ID_KNIHY`)
);
CREATE TABLE `KOPIA_KNIHY` (
`ID_KNIHY` INTEGER NOT NULL,
`KOD_JAZYKA` CHAR(3) NOT NULL,
`ID_KOPIE` INTEGER NOT NULL,
`ORAZKY_V_KNIHE` CHAR(1) NOT NULL 
CHECK (`OBRAZKY_V_KNIHE` IN ("A", "N")),
INDEX(`ID_KOPIE`),
PRIMARY KEY (`ID_KNIHY`, `KOD_JAZYKA`, `ID_KOPIE`),
CONSTRAINT `idx_1` FOREIGN KEY `idx_1` (`ID_KNIHY`) REFERENCES `KNIHA`(`ID_KNIHY`) ON UPDATE CASCADE ON DELETE CASCADE
);

CREATE TABLE `SKLAD` (
`ID_KNIHY` INTEGER NOT NULL,
`ID_KOPIE` INTEGER NOT NULL,
`ID_BUDOVY` INTEGER NOT NULL,
`CISLO_MIESTNOSTI` NUMERIC(4,0) NOT NULL,
`CISLO_REGALU` NUMERIC(4,0) NOT NULL,
PRIMARY KEY(`ID_KNIHY`, `ID_BUDOVY`, `ID_KOPIE`),
CONSTRAINT `idx_2` FOREIGN KEY `idx_2` (`ID_KOPIE`) REFERENCES `KOPIA_KNIHY`(`ID_KOPIE`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `idx_3` FOREIGN KEY `idx_3` (`ID_KNIHY`) REFERENCES `KNIHA`(`ID_KNIHY`) ON UPDATE CASCADE ON DELETE CASCADE
);

在SQLFiddle上试一试
.

相关问题