Nullable Foreign Key bad practice?

前端 未结 11 873
猫巷女王i
猫巷女王i 2020-11-28 03:51

Let\'s say you have a table Orders with a foreign key to a Customer Id. Now, suppose you want to add an Order without a Customer Id, (whether that should be possible is anot

11条回答
  •  隐瞒了意图╮
    2020-11-28 04:16

    Optional relationships are definitely possible in the relational model.

    You can use nulls to express the absence of a relationship. They are convenient, but they will cause you the same headaches that nulls cause you elsewhere. One place where they don't cause any trouble is joins. Rows that have a null in the foreign key don't match any rows in the referenced table. So they drop out of an inner join. If you do outer joins, you are going to be dealing with nulls anyway.

    If you really want to avoid nulls (6th normal form), you can decompose the table. One of the two decomposed tables has two foreign key columns. One is the optional foreign key you have, and the other is a foreign key referencing the primary key of the original table. Now you have to use constraints to prevent the relationship from becoming many-to-many, it you want to prevent that.

提交回复
热议问题