Question

If I have a TABLE that consists of a LIST of attributes of one TYPE and another TABLE that is also composed by the same TYPE of LIST, so how can I implements them into MySQL without having to create two TABLES of the same TYPE?

For example:

Class Diagram

Like the EMPLOYEE table, the COMPANY table has a list of ADDRESSES.

And I want to implement without having to make one table ADDRESS for COMPANY and another for EMPLOYEE, as in this case:

Class Diagram

To me the solution seems to be a dual relationship where one of the foreign keys must be null while the other may not be, but I don't even know how to do it.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top