问题描述
这是我的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,"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,900000);
但是它给出了这个错误
Error adding record. Message from database engine:
foreign key mismatch - "terms_table" referencing "year_table" (INSERT INTO
"main"."terms_table"
("year",900000);)
我正在将dB浏览器用于sqlite
我在做什么错了?
解决方法
来自Required and Suggested Database Indexes:
通常,外键约束的父键是主键 父表的如果它们不是主键,则父键 键列必须共同受到UNIQUE约束,或者 具有唯一索引。
您在代码中做错的是在CREATE
的{{1}}语句中:
terms_table
您在其中定义列FOREIGN KEY("student_id") REFERENCES "year_table"("student_id")
以引用student_id
中没有student_id
约束或索引的列year_table
。UNIQUE
中的列student_id
仅引用了year_table
的列student_id
。
您可以做的是定义student_table
的列student_id
以引用terms_table
中的列student_id
,这很有意义:
student_table
请参见demo。