How to provide constraint to an associative table relating to two source tables with a common foreign key?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 02:24:26

问题


Example scenario.

In a flight schedule system, there are a pilot table which refers to a plane_type table indicating the planes the pilot is able to fly (assuming that is a many-to-one relation).

There are also a plane table and it refers to the plane_type table to indicate the plane's type (also many-to-one relation).

Now there is an associative table flight_plan which assigns a pilot to a plane for a given flight.

How do I make sure the pilot's qualification do match the plane's type for this flight?

Any possibility to implement this as a constraint in a database design? Thank you.

Edited:

Refering to the diagram below, how to make sure pilot.plane_type is equal to plane.plane_type?


回答1:


Plane has unique index (AK) on PlaneID, PlaneTypeID

EDIT

create table Pilot (PilotID integer);
alter table Pilot add constraint PK_Pilot primary key (PilotID);

create table PlaneType (PlaneTypeID integer);
alter table PlaneType add constraint PK_PlaneType primary key (PlaneTypeID);

create table PilotQualification (PilotID integer, PlaneTypeID integer);
alter table PilotQualification 
  add constraint  PK_PilotQual primary key (PilotID, PlaneTypeID)
, add constraint FK1_PilotQual foreign key (PilotID)     references Pilot(PilotID)
, add constraint FK2_PilotQual foreign key (PlaneTypeID) references PlaneType(PlaneTypeID) ;

create table Plane (PlaneID integer, PlaneTypeID integer);
alter table Plane
  add constraint  PK_Plane primary key (PlaneID)
, add constraint FK1_Plane foreign key (PlaneTypeID) references PlaneType(PlaneTypeID) ;
create unique index AK_Plane on Plane (PlaneID, PlaneTypeID) ;

create table PlanePilot (PlaneID integer, PlaneTypeID integer, PilotID integer) ;
alter table PlanePilot
  add constraint  PK_PlanePilot primary key (PlaneID, PlaneTypeID, PilotID)
, add constraint FK1_PlanePilot foreign key (PilotID, PlaneTypeID) references PilotQualification(PilotID, PlaneTypeID)
, add constraint FK2_PlanePilot foreign key (PlaneID, PlaneTypeID) references Plane(PlaneID, PlaneTypeID)
, add constraint FK3_PlanePilot foreign key (PilotID) references Pilot(PilotID) ;


来源:https://stackoverflow.com/questions/7762485/how-to-provide-constraint-to-an-associative-table-relating-to-two-source-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!