I have a composite primary key table (Maintenance Items). I would like to create another table which maps a parent child relationship between items within this table.
I am not sure how to create the Parent Child Relationship table see below either option 1 or option 2.
NOTE: Our business rules stipulate that a parent child relationship can only exits between maintenance items which share the same maintenance program. This will never change!
Table Maintenance Programs
ProgramCode (Primary Key)
ProgramDescription
Other Columns …
Table Maintenance Items (Composite Primary key Table)
ProgramCode (Composite Primary Key)
MaintenanceCode (Composite Primary Key)
MaintenanceDescription
Other Columns …
Table Parent/Child Maintenance Items (Option 1)
ProgramCode
ParentMaintenanceCode
ChildMaintenanceCode
Table Parent/Child Maintenance Items (Option 2)
ParentProgramCode (Same value as ChildProgramCode)
ParentMaintenanceCode
ChildProgramCode (Same value as ParentProgramCode)
ChildMaintenanceCode
There will be no other columns in the Parent/Child tables it is a relationship mapping table only.
Which is the better option? Option 2 seems to suit best practises but given our buisness rule means we essentially have two columns with exactly the same data (ProgramCode).
The only reason for using an associative entity like you’re suggesting is if you want a many-to-many relationship between maintenance items. If that is what you’re after, then option 1 is what you do. The schema would look like something like
This ensure that all related maintenance items share the same ProgramCode and that a maintenance item cannot map to itself (the check constraint).
However, your problem statement refers to a parent/child relationship, which sounds more like a hierarchy/tree. In this case, the schema you would want would look something like this:
The above says that each maintenance item is related to a single maintenance program; conversely, that each maintenance program has zero or more maintenance items.
Further, that each maintenance item has to zero or 1 parent maintenance items, which must be related to the same maintenance program.
The check constraint says that a given maintenance item may not be its own parent.