1

我有一个由超类型表和子类型表构成的数据库,如下所示:

EVENT
PatientId INTEGER,
DateTime TEXT,
EventTypeCode TEXT,
PRIMARY KEY( PatientId, DateTime, EventTypeCode )

不同类型的事件有自己的表并且具有相同的主键,只是它是外来的。

EXERCISE
PatientId INTEGER,
DateTime TEXT,
EventTypeCode TEXT,
PRIMARY KEY( PatientId, DateTime, EventTypeCode ) ON CONFLICT IGNORE,
CONSTRAINT "PrimaryKey" FOREIGN KEY ("PatientId", "EventTypeCode", "DateTime") REFERENCES "Event" ("PatientId", "EventTypeCode", "DateTime") ON DELETE CASCADE ON UPDATE CASCADE

当我尝试在事件中删除一个条目时,我得到一个外键不匹配,当我在练习中删除它时它会删除,但在练习中..它不会级联。我需要做什么才能使级联正常工作?我宁愿删除 Event 中的条目并将其级联到Exercise ..从我看到的示例中看起来它应该如何工作......

4

1 回答 1

1

这是因为您设置了无效的外键。尽管 SQLite 允许您设置它,但在尝试执行它时会出错。

http://www.sqlite.org/foreignkeys.html#fk_indexes

在外键约束中命名的父键列不是父表的主键,并且不受使用 CREATE TABLE 中指定的整理顺序的唯一约束

应针对唯一目标设置外键。该列PatientId references Event(PatientID)无效,因为 Event 表中的 PatientID 单独不是唯一的。


编辑

外键支持仅在 SQLite 3.6.19 或更高版本上可用。根据您使用的工具,您还需要pragma foreign_keys 显式启用. 例如,对于 Firefox 的 SQLite Manager 插件,请参见此处http://code.google.com/p/sqlite-manager/wiki/ForeignKeys


这对我
有用 如果它们包含任何重要的内容,请不要删除现有的表。尝试新的数据库

drop table if exists event;
drop table if exists exercise;

create table EVENT (
PatientId INTEGER,
DateTime TEXT,
EventTypeCode TEXT,
PRIMARY KEY( PatientId, DateTime, EventTypeCode ));
create table EXERCISE(
PatientId INTEGER,
DateTime TEXT,
EventTypeCode TEXT,
PRIMARY KEY( PatientId, DateTime, EventTypeCode ) ON CONFLICT IGNORE,
CONSTRAINT "PrimaryKey" FOREIGN KEY ("PatientId", "EventTypeCode", "DateTime") REFERENCES "Event" ("PatientId", "EventTypeCode", "DateTime") ON DELETE CASCADE ON UPDATE CASCADE);
insert into Event (patientid, datetime, eventtypecode) values (1,2,3);
insert into Event (patientid, datetime, eventtypecode) values (4,5,6);
insert into Event (patientid, datetime, eventtypecode) values (7,9,8);
insert into Exercise (patientid, datetime, eventtypecode) values (1,2,3);
insert into Exercise (patientid, datetime, eventtypecode) values (7,9,8);

delete from event where patientid=1;
于 2011-03-20T21:17:23.667 回答