问题
I have two parent tables: Treatment
and Visit
.
Treatment table:
create table Treatment (
TreatCode CHAR(6) constraint cTreatCodeNN not null,
Name VARCHAR2(20),
constraint cTreatCodePK primary key (TreatCode),
);
Visit table:
create table Visit (
SlotNum NUMBER(2),
DateVisit DATE,
ActualArrivalTime DATE,
constraint cVisitSlotDatePK primary key (SlotNum, DateVisit)
);
Now I try to create a child table:
create table Visit_Treat (
TreatCode constraint cTreatCodeFK references Treatment(TreatCode),
SlotNum constraint cSlotNumFK references Visit(SlotNum),
DateVisit constraint cDateFK references Visit(DateVisit),
constraint cVisitTreatPK primary key (SlotNum, TreatCode, DateVisit)
);
Everything executes fine till the 3 line. Starting from the 3rd line, i.e. SlotNum constraint ...
there is a message: no matching unique or primary key
. There was already a similar question, but i did not quite get the logic to apply in my case. I reference each column one by one, and it works for the Treatment
table parent. How should i correct reference Visit
table parent?
回答1:
CONSTRAINT fk_column
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
in your case
create table Visit_Treat (
TreatCode CHAR(6) constraint cTreatCodeFK references Treatment(TreatCode),
SlotNum NUMBER(2),
DateVisit DATE,
constraint cVisitTreatPK primary key (SlotNum, TreatCode, DateVisit),
constraint fk_slotnumDatevisit FOREIGN KEY(SlotNum,DateVisit)
references Visit(SlotNum,DateVisit)
);
回答2:
A foreign key must reference the primary key of the parent table - the entire primary key. In your case, the Visit
table's primary key is SlotNum, DateVisit
but the foreign key from Visit_Treat
only references SlotNum
.
You have two good options:
Add a
DateVisit
column toVisit_Treat
and have the foreign key beSlotNum, DateVisit
, referencingSlotNum, DateVisit
inVisit
.Create a non-business primary key on
Visit
(for example a column namedVisitID
of typeNUMBER
, fed by a sequence), add aVisitID
column toVisit_Treat
, and make that the foreign key.
And two bad options:
Change the
Visit
primary key to be onlySlotNum
so yourVisit_Treat
foreign key will work. This probably isn't what you want.Don't use a foreign key. I don't recommend this option. If you're having trouble setting up a foreign key that you know should exist, it generally means a design problem.
来源:https://stackoverflow.com/questions/17204845/sql-how-to-reference-a-composite-primary-key-oracle