Does it ever make sense to have more than one fore

2020-04-11 10:27发布

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

2条回答
Anthone
2楼-- · 2020-04-11 11:17

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),
  ...
);
查看更多
放我归山
3楼-- · 2020-04-11 11:20

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.

查看更多
登录 后发表回答