使用像您一樣的關聯實體的唯一原因是如果您想要維護項目之間的多對多關係。如果這就是你所追求的,那麼選項1就是你所做的。該模式將類似於像
create table MaintenanceProgram
(
ProgramCode int not null ,
... -- other non-key attributes here
primary key (ProgramCode) ,
)
create table MaintenanceItem
(
ProgramCode int not null ,
MaintenanceCode int not null ,
... -- other non-key attributes here
primary key (ProgramCode , MaintenanceCode) ,
foreign key (ProgramCode)
references MaintenanceProgram (ProgramCode) ,
)
create table MaintenanceItemMap
(
ProgramCode int not null ,
ParentMaintenanceCode int not null ,
ChildMaintenanceCode int not null ,
primary key (ProgramCode , ParentMaintenanceCode , ChildMaintenanceCode) ,
foreign key (ProgramCode , ParentMaintenanceCode)
references MaintenanceItem (ProgramCode , MaintenanceCode ) ,
foreign key (ProgramCode , ChildMaintenanceCode )
references MaintenanceItem (ProgramCode , MaintenanceCode ) ,
check (ParentMaintenanceCode != ChildMaintenanceCode) ,
)
這確保所有相關的維修項目共享相同的程序代碼和保養項目不能映射到它本身(檢查約束)。
但是,您的問題陳述引用了父/子關係,這聽起來更像是層次結構/樹。在這種情況下,你會想的模式會是這個樣子:
create table MaintenanceProgram
(
ProgramCode int not null ,
... -- other non-key attributes here
primary key (ProgramCode) ,
)
create table MaintenanceItem
(
ProgramCode int not null ,
MaintenanceCode int not null ,
ParentMaintenanceCode int null ,
... -- other non-key attributes here
primary key (ProgramCode , MaintenanceCode) ,
foreign key (ProgramCode )
references MaintenanceProgram ( ProgramCode) ,
foreign key (ProgramCode , ParentMaintenanceCode)
references MaintenanceItem (ProgramCode , MaintenanceCode ) ,
check (MaintenanceCode != ParentMaintenanceCode or ParentMaintenanceCode is null) ,
)
上面說,每個保養項目是關係到一個單一的維修方案;相反,每個維護程序都有零個或多個維護項目。
此外,每個維護項目必須有零個或1個父級維護項目,這些項目必須與相同的維護程序相關。
檢查約束表明給定的維護項目可能不是其自己的父項。
毫無疑問,您的頂級架構是我所追求的。需要成爲多對多的關係。謝謝! – Reafidy