开发者

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

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?

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


Plane has unique index (AK) on PlaneID, PlaneTypeID

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

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) ;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜