I believe your underlying hyopthesis is flawed: a one-person Company
, founded by an Employee
, could be registered at the founder's personal adress. Therefore an Employee
may have the same address as a Company
.
Likewise, two Employees
may share the same address (a husband and a wife could be coworkers). Therefore I would define the relationship between adress
and each of the other two entities a regular many-to-many, without any further condition.
You might be worried that changing the address of (eg.) a Company
would wrongly alter the Employee
's address. But instead of updating the Address
entity, treat this case as creating a new Address
and linking the (eg.) Company
to this new Address
.
Now, if you really need to implement the constraint, regardless of the (oh so dull ;) reality, I see no other option but implementing a form of inheritance as decribed here.
Notice that:
- your initial design actually implements the Single Table Inheritance pattern
- your alternative proposal (based on two separate
address
tables) actually implements the Concrete Table Inheritance pattern1
In your initial design, the constraint can be implemented with a simple CHECK
constraint2 on the address
table, the condition being company_id IS NULL XOR employee_id IS NULL
1 Migrating to the Class Table Inheritance pattern is "left as an exercise". However this pattern does not help in enforcing this constraint (in fact, this elegant pattern has serious additional limitations with enforcing integrity constraints in general). Nevertheless the constraint could still be enforced with a CHECK
constraint.
2 MySQL does not enforce CHECK
constraints, but a similar effect can be achieved through the use of triggers.