2011-09-12 58 views
0

我有一個複合主鍵表(維護項目)。我想創建另一個表,它映射此表中項目之間的父子關係。映射覆合主鍵表的父/子關係表

我不知道如何創建父子關係表見下面的選項1或選項2

注:我們的業務規則規定,一個父子關係只能共用維修項目之間退出相同的維護程序。這永遠不會改變!

表維護計劃
的程序代碼(主鍵)
ProgramDescription
其他列...

表維護項目(複合主鍵表)
的程序代碼(複合主鍵)
維護代碼(複合主鍵)
維護說明
其他列...

表父/子維​​護項目(選項1)
的程序代碼
ParentMaintenanceCode
ChildMaintenanceCode

表父/子維​​護項目(選項2)
ParentProgramCode(與ChildProgramCode相同的值)
ParentMaintenanceCode
ChildProgramCode(同值作爲ParentProgramCode)
ChildMaintenanceCode

會有在父/子表沒有其它列它僅僅是一個關係的映射表。

哪個更好?選項2似乎適合最佳實踐,但鑑於我們的商業規則意味着我們基本上有兩列完全相同的數據(程序代碼)。

回答

2

使用像您一樣的關聯實體的唯一原因是如果您想要維護項目之間的多對多關係。如果這就是你所追求的,那麼選項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個父級維護項目,這些項目必須與相同的維護程序相關。

檢查約束表明給定的維護項目可能不是其自己的父項。

+0

毫無疑問,您的頂級架構是我所追求的。需要成爲多對多的關係。謝謝! – Reafidy

1

爲什麼你認爲選項2是最佳實踐?如果它們必須相同,則將它們放在不同的列中是沒有意義的。選項1是2.中的更好選擇。

+0

這只是我未受教育的想法,感謝您的幫助。 – Reafidy

1

選項1是最好的答案,您可以引用孩子父母(並強制引用完整性)。另外,如果您使用的是SQL Server 2005或更高版本,則可以使用遞歸CTE來構建父級/子級的層次結構(如果菜單,下拉菜單等需要)。

+0

感謝Wil,遞歸CTE可能會成爲我的下一個障礙。 – Reafidy