Does it ever make sense to have more than one foreign keys between two tables

只谈情不闲聊 提交于 2019-12-01 22:44:14

Yes, there are certainly cases where a table can have multiple foreign keys to different rows of a parent table.

Here's an example: A table in a bug-tracking database, which references three different users. The user who reported the bug, the engineer who is assigned to fix the bug, and a tester who is assigned to verify the bug is fixed.

CREATE TABLE Bugs (
  bug_id INT PRIMARY KEY,
  reporter INT NOT NULL REFERENCES Users(user_id),
  assigned_to INT REFERENCES Users(user_id),
  verified_by INT REFERENCES Users(user_id),
  ...
);

If each of those users might be different people, you need a distinct foreign key for each one.

Here's another example: A shipping application tracks each shipment and records the origin country and the destination country.

CREATE TABLE Shipments (
  ...
  origin_country INT NOT NULL REFERENCES Countries(country_id),
  destination_country INT NOT NULL REFERENCES Countries(country_id),
  ...
);

You should know the fact that how many primary keys a table can have and thats one for one table representation. So, the fact that two tables in between them you can have one foreign key as a representation of a unique not null called primary key of the other. But that doesnt mean a table can have only one foreign key Foreign keys might be several in one table to many tables primary keys.

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