1

这是我的 student_table 创建查询

CREATE TABLE "student_table" (
    "student_id"    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    "name"  TEXT NOT NULL,
    "gender"    TEXT NOT NULL,
    "year_admited"  INTEGER
);

这是给我的 year_table

CREATE TABLE "year_table" (
    "year"  INTEGER NOT NULL,
    "student_id"    INTEGER NOT NULL,
    "class" INTEGER NOT NULL,
    PRIMARY KEY("year"),
    FOREIGN KEY("student_id") REFERENCES "student_table"("student_id")
);

这对于terms_table

CREATE TABLE "terms_table" (
    "year"  INTEGER NOT NULL,
    "student_id"    INTEGER NOT NULL,
    "term"  INTEGER NOT NULL,
    "fees"  INTEGER,
    PRIMARY KEY("term","year"),
    FOREIGN KEY("year") REFERENCES "year_table"("year"),
    FOREIGN KEY("student_id") REFERENCES "year_table"("student_id")
);

我成功地在 student_table 和 year_table 中插入了一行

我尝试将值添加到术语表

INSERT INTO "main"."terms_table"
("year", "student_id", "term", "fees")
VALUES (2020, 1, 1, 900000);

但它给出了这个错误

Error adding record. Message from database engine:

foreign key mismatch - "terms_table" referencing "year_table" (INSERT INTO 
"main"."terms_table"
("year", "student_id", "term", "fees")
VALUES (2020, 1, 1, 900000);)

我正在为 SQLite 使用 dB 浏览器

我究竟做错了什么?

4

1 回答 1

0

所需和建议的数据库索引

通常,外键约束的父键是父表的主键。如果它们不是主键,则父键列必须共同受 UNIQUE 约束或具有 UNIQUE 索引。

您在代码中做错的CREATEterms_table

FOREIGN KEY("student_id") REFERENCES "year_table"("student_id")

您在其中定义列以student_id引用没有约束或索引的列。中 的列仅引用 的列。student_idyear_tableUNIQUE
student_idyear_tablestudent_idstudent_table

您可以做的是定义列student_idterms_table引用 中的列student_idstudent_table这是有道理的:

FOREIGN KEY("student_id") REFERENCES "student_table"("student_id")

请参阅演示

于 2020-11-10T19:39:46.837 回答