为什么在尝试将父 table 中的唯一值插入子项时出现外键不匹配?

Why am I getting a foreign key mismatch when trying to insert unique values from parent table into child?

我试图将 Main_StandardsSubject 字段的唯一值插入到 SubjectsName 字段中,这是一个引用 Subject 字段。

这是我的 Main_Standards table:

CREATE TABLE "Main_Standards" (
    "ID"    INTEGER NOT NULL UNIQUE,
    "Subfield"  TEXT NOT NULL,
    "Domain"    TEXT NOT NULL,
    "Code"  INTEGER NOT NULL UNIQUE,
    "Standard_Type" TEXT NOT NULL,
    "Assessment_Type"   TEXT NOT NULL,
    "Subject"   TEXT,
    "Subject_Reference" TEXT,
    "Title" TEXT NOT NULL,
    "Level" INTEGER NOT NULL,
    "Credits"   INTEGER NOT NULL,
    "Grading_Scheme"    TEXT NOT NULL,
    "Status"    TEXT NOT NULL,
    "Expiry_Date"   TEXT,
    "Publication_Date"  TEXT NOT NULL,
    "CurrentVersion"    INTEGER NOT NULL,
    "Hyperlink" TEXT,
    PRIMARY KEY("ID" AUTOINCREMENT)
)

这是我的 Subjects table.

CREATE TABLE "Subjects" (
    "ID"    INTEGER NOT NULL UNIQUE,
    "Name"  TEXT NOT NULL UNIQUE,
    "Subfield"  TEXT NOT NULL,
    "Selected"  TEXT NOT NULL DEFAULT 'False',
    FOREIGN KEY("Name") REFERENCES "Main_Standards"("Subject"),
    PRIMARY KEY("ID" AUTOINCREMENT)
)

这是导致抛出错误的查询:

INSERT OR IGNORE INTO Subjects(Name, Subfield)
SELECT DISTINCT
Subject, 
Subfield
FROM Main_Standards
WHERE Standard_Type = 'A';

错误本身:

Execution finished with errors.
Result: foreign key mismatch - "Subjects" referencing "Main_Standards"
At line 1:
INSERT OR IGNORE INTO Subjects(Name)
SELECT DISTINCT
Subject
FROM Main_Standards
WHERE Standard_Type = 'A';

来自the documentation

Usually, the parent key of a foreign key constraint is the primary key of the parent table. If they are not the primary key, then the parent key columns must be collectively subject to a UNIQUE constraint or have a UNIQUE index.

Main_Standards.Subject 不是 table 的 PK,您也没有任何迹象表明它上面有唯一索引。因此,当您尝试将其用作父键时出错。


无关,但PRIMARY KEY根据定义是独一无二的。您不需要同时指定 UNIQUE 。这样做是悲观的,因为它创建了一个冗余索引,每次修改 table 时都必须更新该索引。