我正在为治疗计划软件建模三个实体的层次结构。治疗基本上被理解为在若干天内给予患者的许多药物。我希望能够在任何一天取消治疗,只能以一次性写入(用于质量控制认证)。
以下是具体问题:将复合外键的一部分重用为另一个外键是否可以?在我的情况下,复合关键点从药物表到日历表,然后指向治疗。治疗ID包含在药物表中的复合外键中,因此我可以将其用作外键,使查询更容易?
表定义应该是这样的(我的原始SQL技能中的模数hickups,我通常总是使用某种ORM):
CREATE TABLE therapy (
"id" INTEGER NOT NULL,
"start" DATE NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE day (
"therapy_id" INTEGER NOT NULL,
"day" INTEGER NOT NULL,
"revision" INTEGER NOT NULL,
"comment" TEXT;
"cancelled" BOOLEAN NOT NULL;
PRIMARY KEY (therapy_id, day, revision),
FOREIGN KEY(therapy_id) REFERENCES therapy (id)
);
CREATE TABLE medication (
"id" INTEGER NOT NULL,
"therapy_id" INTEGER NOT NULL,
"day" INTEGER NOT NULL,
"revision" INTEGER NOT NULL,
"substance" VARCHAR(100) NOT NULL,
"dosage" VARCHAR(50) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY(therapy_id, day, revision) REFERENCES day (therapy_id, day, revision),
-- wondering if this is ok
FOREIGN KEY(therapy_id) REFERENCES therapy (id)
);
请注意,从一天到药物的关系是一对多,例如在第3天,我想用布洛芬,扑热息痛,阿司匹林,磨碎的咖啡豆和Jaegermeister的良好注射剂给患者涂抹膏药。
答案 0 :(得分:1)
这是你的开始。
CREATE TABLE medication (
"id" INTEGER NOT NULL, -- You don't need this.
"therapy_id" INTEGER NOT NULL,
"day" INTEGER NOT NULL,
"revision" INTEGER NOT NULL,
"substance" VARCHAR(100),
"dosage" VARCHAR(50),
PRIMARY KEY (id), -- Drop this.
FOREIGN KEY(therapy_id, day, revision)
REFERENCES day (therapy_id, day, revision), -- Ok, but should be PK.
FOREIGN KEY(therapy_id) REFERENCES therapy (id) -- You don't need this.
);
列“id”没有任何用处,而是让您确信您不需要对真实键的唯一约束:{therapy_id,day,revision}。使用{therapy_id,day,revision}上的主键约束替换“id”上的无用主键约束。删除最后一个外键约束。您知道“therapy_id”将引用现有行,因为表“day”中的外键约束需要它。
这让我们留下了这个。
CREATE TABLE medication (
"therapy_id" INTEGER NOT NULL,
"day" INTEGER NOT NULL,
"revision" INTEGER NOT NULL,
"substance" VARCHAR(100),
"dosage" VARCHAR(50),
PRIMARY KEY (therapy_id, day, revision),
FOREIGN KEY(therapy_id, day, revision)
REFERENCES day (therapy_id, day, revision)
);
让我感到困惑的是“物质”和“剂量”可以为空。想一想。