Any example of a necessary nullable foreign key?

后端 未结 8 1728
感情败类
感情败类 2020-12-03 01:42
Customers
 customer_id

Orders
 order_id
 customer_id fk

If I have two tables and define a foreign key on customer_id in the Orders table, by allow

8条回答
  •  执笔经年
    2020-12-03 02:04

    No, nullable foreign keys are never necessary.

    You can always normalize an optional 1-many relationship. Taking your example, you may have the following tables:

    Customers: customer_id, ...
    Orders: order_id, ...
    OrdersCustomers: order_id, customer_id
      UNIQUE(order_id)
    

    The two unique constraints make sure that one order can belong to only one customer, and never to the same customer twice.

    Whether you should always normalize such a relationship is a different story. In some cases denormalization may lead to simpler implementations.

提交回复
热议问题