Note that there are some explanatory texts on larger screens.

plurals
  1. PODual use of composite foreign keys
    primarykey
    data
    text
    <p>I'm modelling a hierarchy of three entities for a therapy planning software. A therapy is basically understood as a number of medications that are given to a patient on a number of days. I want to be able to cancel therapy on any given day, in a write-only-once fashion (for quality control certification purposes).</p> <p>Here's the concrete question: Is it ok to reuse a part of a composite foreign key as a another foreign key? In my case the composite key points from the medication table to the day table, which then points back to the therapy. The therapy id is included in the composite foreign key in the medication table, so I could use this as a foreign key, making querying more easy?</p> <p>The table definitions should be something like this (modulo hickups in my raw SQL skills, I usually always employ some kind of ORM):</p> <pre class="lang-sql prettyprint-override"><code>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) ); </code></pre> <p>Please note that the relation from day to medication is one-to-many, e.g. on day 3 I want to plaster the patient with a deadly mix of Ibuprofen, Paracetamol, Aspirin, ground up coffee beans and a good shot of Jaegermeister.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload