我有以下表格:(注意SUPP可能为NULL(
CREATE TABLE IF NOT EXISTS A
(
ID INTEGER PRIMARY KEY NOT NULL
);
CREATE TABLE IF NOT EXISTS B
(
ID INTEGER PRIMARY KEY NOT NULL
);
CREATE TABLE IF NOT EXISTS C
(
ID INTEGER PRIMARY KEY NOT NULL
);
CREATE TABLE IF NOT EXISTS D
(
SID INTEGER NOT NULL,
DID INTEGER NOT NULL,
SUPP INTEGER,
PRIMARY KEY (SID, DID),
FOREIGN KEY (SID) REFERENCES A (ID),
FOREIGN KEY (DID) REFERENCES B (ID),
FOREIGN KEY (SUPP) REFERENCES C (ID)
);
假设表A包含ID=2,而表B包含ID=5。我想执行以下插入:
INSERT OR REPLACE INTO D VALUES (2,5,NULL);
然而,我得到以下错误:
外键不匹配-D引用C(INSERT INTO"main"."D"…
我假设问题源于NULL外键,但我不知道我做错了什么,也不知道如何修复它。
如果要插入子表,则需要使用有效的引用值。表A中的ID 2和表B中的ID 5必须存在。
CREATE TABLE IF NOT EXISTS A
(
ID INTEGER PRIMARY KEY NOT NULL
);
CREATE TABLE IF NOT EXISTS B
(
ID INTEGER PRIMARY KEY NOT NULL
);
CREATE TABLE IF NOT EXISTS C
(
ID INTEGER PRIMARY KEY NOT NULL
);
CREATE TABLE IF NOT EXISTS D
(
SID INTEGER NOT NULL,
DID INTEGER NOT NULL,
SUPP INTEGER,
PRIMARY KEY (SID, DID),
FOREIGN KEY (SID) REFERENCES A (ID),
FOREIGN KEY (DID) REFERENCES B (ID),
FOREIGN KEY (SUPP) REFERENCES C (ID)
);
INSERT INTO A VALUES (2);
INSERT INTO B VALUES (5);
INSERT INTO D VALUES (2, 5, NULL);