Consider this case where I'm trying to model a database for a company:
- Entities:
Employees
,Managers
,Departments
. - An
Employee
works in only 1Department
while aDepartment
may have manyEmployees
working in it. - A
Manager
may manage only 1Department
and similarly aDepartment
may have only 1Manager
. - A
Manager
supervises manyEmployees
, but anEmployee
is only supervised by oneManager
.
Now I have 2 ways to model this:
First solution:
I'll consider that the Manager
entity inherits from the Employee
entity considering that I'll keep data that is unique to the Managers (e.g. Bonus & Status).
-
Since the relation between
Department
andEmployee
is1:N
then I'll put the
Department Id
as a foreign key in theEmployee
table for theWorks
relation. -
Since the relation between
Department
andManager
is1:1
then I'll put the
Department Id
as a foreign key in theManager
table for theManages
relation.
Problem: How can I represent the recursive relation between the Manager
and Employee
?
Second solution:
I'll consider that the Manager
entity is not needed as other Employees
may also have a Bonus
and Status
. (Actually I added these 2 attributes just to see how to model it in both cases)
- Since the relation between
Department
andEmployee
is1:N
then I'll put the
Department Id
as a foreign key in theEmployee
table for theWorks
relation. - Since the relation between
Employee
andManager
is1:N
then I'll put the
Employee Id
as a foreign key in theEmployee
table for theSupervises
relation and call itManager Id
.
Problem: How can I represent the relation between the Manager
and Department
?
Questions:
- Is there any obvious mistakes in both design as they are?
- How to solve each problem in both cases?
- Is there a better solution than these two?
Best Answer
I'd probably go with something like:
This model has the following characteristics:
NOTE: If your DBMS does not support deferred constraints, you'll want to make the DEPARTMENT.MANAGER_ID NULL-able, to break the cycle that would otherwise prevent you from inserting the new data.
If the departments are required to match, then you'd either employ a DBMS-specific technique (such as triggers or "special" constraints), or "propagate" the DEPARTMENT_ID into the PK of employees. This propagation is what ultimately enables the matching:
Since EMPLOYEE_ID must be globally unique, it cannot stay in the composite key together with the DEPARTMENT_ID. So, we make it alternate key and instead use the surrogate EMPLOYEE_NO in the PK.
This model prevents you from having a manager that manages one department and works in another, or a supervisor that supervises employees from a different department.
In case you are not familiar with the symbol...
...it denotes a "category". In this context, you can simply interpret it as a "1 to 0 or 1" relationship between EMPLOYEE and MANAGER.