What is the best design for a database table that can be owned by two different resources, and therefore needs two different foreign keys? [closed]

Generally, there are two strategies to handle a situation like this:

  1. Use Exclusive FKs

Essentially, each of the possible parent tables will have its own, separate foreign key in the child table, and there is a CHECK enforcing exactly one of them is non-NULL. Since FKs are only enforced on non-NULL fields (meaning, when a FK is set to NULL there is no database-level validation), only one of the FKs will be enforced.

For example:

enter image description here

(relationship between user and group omitted)

CHECK (
    (group_id IS NOT NULL AND user_id IS NULL)
    OR (group_id IS NULL AND user_id IS NOT NULL)
)
  1. Use Inheritance

Inherit user and group from a common supertype and then connect the setting to the supertype:

enter image description here

For more information on inheritance (aka. category, subclassing, subtype, generalization hierarchy etc.), take a look at “Subtype Relationships” chapter of ERwin Methods Guide. Unfortunately, modern DBMSes don’t natively support inheritance – for some ideas about physically implementing it, take a look at this post.

This is a heavy-duty solution probably not justified for just two tables (groups and users), but can be quite “scalable” for many tables.

Leave a Comment