I’ve got table Visit with columns like VisitID, PatientID, DoctorID etc. and also column PrescriptionID. In table Prescription there are columns PrescriptionID and DrugID (together they are my primary key). One prescription can have many drugs, so there will be something like:
PrescriptionID: 1 DrugID: 38
PrescriptionID: 1 DrugID: 278
PrescriptionID: 1 DrugID: 7
In Visit table there will be inserted ‘1’ value as PrescriptionID. But now I can’t join those two tables with foreign key, because not every visit have prescription, so PrescriptionID can be null and I’ve got error that column must be primary key or must be unique. How can I join those tables in another way?
You seem to be talking about two distinct issues here.
One issue is, you want to allow nulls in a referencing column. That is easy, you just need to define the column as nullable and as a foreign key. What that key should reference is another question, which leads us to the other of the two issues I can see in your question.
The error about the column having to be primary key or unique has to do with the fact that the referencing table uses a single column to reference a compound (consisting of two columns) key. And you can’t reference only part of the key, because a reference must be to a specific single row and your
Visit.PrescriptionIDvalue is likely to reference more than one (and rightly so, because the rows in the referenced table aren’t really prescriptions, but prescription items). That is why you are told that the column must be primary key or unique.Therefore, I suggest changing your schema as follows:
Let your
Prescriptiontable contain only prescriptions as entities. Even if there are no other attribute than a key, let it be stored in its own table:Your present
Prescriptiontable should be renamed to something likePrescriptionItemorPrescriptionDrug, following your singular noun naming convention. ItsPrescriptionIDcolumn would be a foreign key referencingPrescription.PrescriptionID, something like this:Now you can define the foreign on
Visit.PrescriptionIDlike this:Don’t forget to make sure the column is nullable if you want to make prescriptions optional for visits. (Nullable foreign keys are perfectly fine in SQL Server.)