Difference between one-to-one and one-to-many relationship in database

后端 未结 8 1320
执念已碎
执念已碎 2021-02-01 06:13

This is probably a basic(dumb) question but when having a one-to-one relationship in a database the other table has a foreign key ID(in this example). And in a one-to-many relat

相关标签:
8条回答
  • 2021-02-01 06:44

    well, you are right, this relation is important for you, but not for db itself. When you have two tables, one with your basic information, and another one with your detailed information.. for both tables you are you, so it is one-to-one relation, you can not map your data to somebody else.

    Now add third table "cities" and one of your information points to city you live in - this is example of one-to-many (one city can be used, and should be used for many people).

    one-to-many / one-to-one just show how your tables interact. And all the time, you want to "save" rows/columns in table not duplicating them you will use one-to-many relation with another table. Or many-to-many :)

    0 讨论(0)
  • 2021-02-01 06:46

    Let's assume you have a table with two attributes A and B. If A is a candidate key and B is not then the relationship between A and B is 1 to many. If both A and B are candidate keys then the relationship is 1 to 1.

    0 讨论(0)
  • 2021-02-01 06:51

    The database-level equivalent of a 1:1 vs. 1:m is having a unique index on the foreign key column. Note that this will only work for 1:1, NOT 1:0..1, as null is considered when evaluating uniqueness. There are workarounds for this restriction, but that's it at the basic level.

    0 讨论(0)
  • 2021-02-01 06:57

    To enable one-to-one relationship you need to add unique constraint to foreign key. It is not possible to have two foreign keys for each table as it will be impossible to create records.

    0 讨论(0)
  • 2021-02-01 07:00

    Similarly by example, a product has only one product code, so it's one-to-one relationship (product <-> ABC123), but a customer can purchase more than one product, so it's one-to-many relationship (person <->>>product).

    0 讨论(0)
  • 2021-02-01 07:01

    Given table A and B if

    1. A and B have a strict 1 to 1 relationship
    2. For every B instance, there will always be an A instance

    The best approach is to make the primary key of B also a foreign key referencing A. This is also called "Table per Type Inheritance" and the "is a" relationship. There are other ways to enforce a unique foreign key, but using the primary key makes the relationship clear in the schema and in ER diagrams.

    Of course there are always other scenarios, and if your design doesn't meet both of the criteria above, you'll have to use another approach.

    0 讨论(0)
提交回复
热议问题