When I should use one to one relationship?

后端 未结 13 1578
面向向阳花
面向向阳花 2020-11-27 11:32

Sorry for that noob question but is there any real needs to use one-to-one relationship with tables in your database? You can implement all necessary fields inside one table

13条回答
  •  春和景丽
    2020-11-27 11:39

    First, I think it is a question of modelling and defining what consist a separate entity. Suppose you have customers with one and only one single address. Of course you could implement everything in a single table customer, but if, in the future you allow him to have 2 or more addresses, then you will need to refactor that (not a problem, but take a conscious decision).

    I can also think of an interesting case not mentioned in other answers where splitting the table could be useful:

    Imagine, again, you have customers with a single address each, but this time it is optional to have an address. Of course you could implement that as a bunch of NULL-able columns such as ZIP,state,street. But suppose that given that you do have an address the state is not optional, but the ZIP is. How to model that in a single table? You could use a constraint on the customer table, but it is much easier to divide in another table and make the foreign_key NULLable. That way your model is much more explicit in saying that the entity address is optional, and that the ZIP is an optional attribute of that entity.

提交回复
热议问题