Where should I store a foreign key?

后端 未结 4 577
猫巷女王i
猫巷女王i 2021-01-31 09:52

If I have a relationship between two tables (both tables have their own primary keys) what should guide my decision as to which table should store the foreign key? I understand

4条回答
  •  天涯浪人
    2021-01-31 10:24

    A foreign key is simply a field in one table that refers to a key field of another table. It's not absolutely critical to identify the foreign key field as such. That is, you don't need to explicitly add the FOREIGN KEY ... REFERENCES constraint to the table for it to be a foreign key. When you join the two tables together, the primary key of the parent table will be set equal to the foreign key of the child table. Whichever one is not the primary key is the foreign key.

    In one-to-many relationships, the FK goes on the "many" side. It can't go on the "one" side because that's where the PK goes and the definition of a primary key includes disallowing duplicates.

    If you have a many-to-many relationship, you'll need to re-work the tables so you end up with two one-to-many relationships and an intermediate resolution table.

提交回复
热议问题