是什么导致sqlite数据库中的外键不匹配错误

问题描述

这是我的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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...