1

我的 SQLite 3 具有以下设置(简化):

create table Location(LocationId integer not null,
                      LocationCode text not null, 
                      primary key(LocationId),
                      unique(LocationCode));

上表由部门参考:

create table Department(DepartmentId integer not null,
                        LocationId integer not null,
                        DepartmentCode text not null,
                        primary key(LocationId, DepartmentCode),
                        foreign key(LocationId) references Location(LocationId));

上表被 Child 引用:

create table Event(EventId integer not null,
                   LocationId integer not null,
                   unique(LocationId, EventDate),
                   primary key(eventId),
                   foreign key(LocationId) references Location(LocationId));

上表参考表位置:

create table Parent(ParentId integer not null,
                    EmailAddress text not null,
                    primary key(ParentId),
                    unique(EmailAddress));

上表被表 Child 引用:

create table Child(ChildId integer not null,
                   ParentId integer not null,
                   ChildCode text not null,
                   DepartmentId integer not null,
                   primary key(ChildId, ParentId),
                   foreign key(ParentId) references Parent(ParentId),
                   foreign key(DepartmentId) references Department(DepartmentId));

表子是我要从中删除的那个。

此时,整个数据库是空的,并且有“pragma foreign_keys=ON”。

Child在测试脚本以清除数据库时,我在从具有外键的空表中删除(也是空的)表时遇到错误Parent

当我发出命令delete from child时(虽然已经为空),SQLite3 会返回错误消息“外键不匹配”。

这是删除脚本的重要部分:

delete from Child;
delete from Parent;
delete from Event;
delete from Department;
delete from Location;

我在这里看到了一些关于暂时禁用外键支持的帖子,但这对我来说没有意义。这使得实现外键关系的整个过程变得不必要。

4

1 回答 1

2

文档(隐藏在源代码中)说:

外键约束要求父表中的键列共同受 UNIQUE 或 PRIMARY KEY 约束。[...] 如果找不到所需的索引,可能是因为:

  1. 命名的父键列不存在,或者
  2. 命名的父键列确实存在,但不受 UNIQUE 或 PRIMARY KEY 约束,或
  3. 没有明确提供作为外键定义的一部分的父键列,并且父表没有 PRIMARY KEY,或者
  4. 没有明确提供作为外键定义的一部分的父键列,并且父表的 PRIMARY KEY 由与子表中的子键不同数量的列组成。

然后......“外键不匹配”错误[引发]。

> DELETE FROM Child;
Error: foreign key mismatch
> CREATE UNIQUE INDEX di ON Department(DepartmentId);
> DELETE FROM Child;
> 
于 2013-03-18T08:16:54.993 回答