Foreign Key column mapped to multiple primary keys

前端 未结 3 1519
再見小時候
再見小時候 2020-12-06 23:37

I have a database which has three tables

Messages - PK = MessageId
Drafts - PK = DraftId
History - FK = RelatedItemId

The History table has a sin

3条回答
  •  无人及你
    2020-12-06 23:56

    Is there a name for this relationship?

    There is no standard name that I'm aware of, but I've heard people using the term "generic FKs" or even "inner-platform effect".

    Is it just bad design?

    Yes.

    The reason: it prevents you from declaring a FOREIGN KEY, and therefore prevents the DBMS from enforcing referential integrity directly. Therefore you must enforce it trough imperative code, which is surprisingly difficult.

    Is there a better way to design this relationship?

    Yes.

    Create separate FOREIGN KEY for each referenced table. Make them NULL-able, but make sure exactly one of them is non-NULL, through a CHECK constraint.

    Alternatively, take a look at inheritance.

提交回复
热议问题