In a SQL database, when should a one-to-one relationship be in the same table and when in separate tables?

风格不统一 提交于 2019-12-11 04:56:49

问题


Can anyone provide some examples of when in a SQL database it's a better choice to keep one-to-one relationships on the same table, and when instead it makes more sense to have them on separate tables?


回答1:


When you have several entities which all must be able to act as a foreign key to another entity, and the "several entities" have both common properties and unique properties, and you want a NOT NULL constraint on the unique properties (or less important don't want a bunch of NULL values for the unique properties not applicable to the other entity). Even if you didn't have the unique/common properties and didn't care about the NULL values, you might still wish to do so if you wanted individual foreign constraints on each subtpye table as well as the supertype table. This strategy is called supertype/subtype modelling.

Let me give you an example.

peoples

  • id (PK)
  • name
  • age

teachers

  • id (PK, and FK to people.id)
  • years_teaching NOT NULL
  • whatever NOT NULL

students

  • id (PK, and FK to people.id)
  • grade NOT NULL
  • whatever NOT NULL

As you see, teachers and students can have a single common table for some of the properties and can each have their own NOT NULL unique properties. Furthermore, you can JOIN people, teachers, and students to other tables and keep referential integrity.

Another application "might" be if you had separate databases for the each record with some of the properties in one and some in the other, however, I have never done this.



来源:https://stackoverflow.com/questions/42183452/in-a-sql-database-when-should-a-one-to-one-relationship-be-in-the-same-table-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!