2011-10-14 30 views
1

示例场景。如何使用公共外键为与两个源表相关的关联表提供约束?

在航班计划系统中,有一个pilot表,它表示plane_type表,表示飞行员能够飞行的飞机(假设这是多对一的关系)。

还有一个plane表,它指的是plane_type表来指示飞机的类型 (也是多对一的关系)。

现在有一个关联表flight_plan,它为给定的航班分配一个pilotplane

我该如何确保pilot的资格证符合plane的这种航班?

有没有可能在数据库设计中实现这个约束?谢谢。

编辑:

指的下图中,如何确保pilot.plane_type等于plane.plane_type

enter image description here

回答

1

PlanePlaneID, PlaneTypeID

enter image description here

编辑

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

心不是该解决方案具有独特的指数(AK)只是保证了每个PlaneType只能有一个平面? –

+0

@CYT NO。每个PlaneType可以有多个Planes。它确保分配给飞机的飞行员具有该飞机的资格。 PLanePilot上的外键是FK1'PlanePilot(PilotID,PlaneTypeID)REFERENCES PilotQualification(PilotID,PlaneTypeID)'和FK2' PlanePilot(PlaneID,PlaneTypeID)REFERENCES Plane(PlaneID,PlaneTypeID)'和FK3' PlanePilot(PilotID)REFERENCES Pilot(PilotID )' –

+0

FK1中的PlaneTypeID和FK2中的PlaneTypeID是PlanePilot中的同一列?如果不是数据库如何确保两列具有相同的值? –