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

北城以北 提交于 2019-12-20 02:37:13

问题


I was learning Sqlalchemy and noticed that a foreign key relation was defined by relating the table names without identifying the actual foreign key connecting the two tables, so I was thinking, if there are more than one foreign keys between the two tables(if it ever makes sense), sqlalchemy would fail to determine the key used to link the two tables. Anyway, my question is: does it ever make sense to have more than one foreign keys between two tables


回答1:


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),
  ...
);



回答2:


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.



来源:https://stackoverflow.com/questions/53917035/does-it-ever-make-sense-to-have-more-than-one-foreign-keys-between-two-tables

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