Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set of Foreign Keys Where All But One Are NULL

What is the name for the technique of using a set of foreign keys in a table where all but one are NULL for a given row?

In other words, each row needs a foreign key to one (and only one) of n different possible tables so you actually have all the necessary foreign keys but all but one are NULL.

(users of Django may recognize this as an alternative to using a Generic Foreign Key)

like image 283
James Tauber Avatar asked Jan 22 '10 13:01

James Tauber


People also ask

Can a foreign key be set to null?

A table can have many foreign keys. A foreign key is nullable if any part is nullable. A foreign key value is null if any part is null.

Can foreign key have multiple null values?

Foreign keys allow key values that are all NULL , even if there are no matching PRIMARY or UNIQUE keys. By default (without any NOT NULL or CHECK clauses), the FOREIGN KEY constraint enforces the match none rule for composite foreign keys in the ANSI/ISO standard.

Under what conditions foreign key must not be null?

A foreign key may not be null when it is part of a composite primary key in the child table.

Are foreign keys automatically NOT null?

@MartinSmith: Well, the question is "Does a foreign key constraint automatically disallow nulls?" and the answer is "No", because "A FOREIGN KEY constraint can contain null values".


2 Answers

The term for the design you're describing is Exclusive Arc.

Instead, I prefer to make one foreign key that references a common super-table of your n different parent tables.

See my other answers for polymorphic associations:

  • Possible to do a MySQL foreign key to one of two possible tables?
  • Referencing foreign keys in the same column
  • Why can you not have a foreign key in a polymorphic association?
  • In a StackOverflow clone, what relationship should a Comments table have to Questions and Answers?
  • How to handle an “OR” relationship in an ERD (table) design?
like image 173
Bill Karwin Avatar answered Sep 24 '22 17:09

Bill Karwin


It would have been easier with a example, but a common way to untangle this is simply to find a common super-type for those tables. Suppose that we have tables Book, Article, Magazine and now a table has to have foreign key to these tables. Using a common super-type Publicationresolves this. See here for the model and the similar question/answer.

like image 36
Damir Sudarevic Avatar answered Sep 25 '22 17:09

Damir Sudarevic