PostgreSQL 中的联结 table

Junction table in PostgreSQL

我有两个table

recipe table
-----------------------
|recipe_id   |name  |
-----------------------
|1           |Pasta |
|2           |Pizza |
|3           |Fish  |


ingredient table
-------------------------------
|ingredient_id   |name        |
-------------------------------
|1               |Spaghetti   |
|2               |Salmon      |
|3               |Tomato sauce|

我创建了一个名为“recipes_ingredients”的联结 table

-------------------------------
|id   |fk_recipe|fk_ingredient|
-------------------------------
|1    |1        |1           |
|2    |2        |3           |
|3    |3        |2           |

我的第一个问题是:我创建“recipes_ingredients”table 的方式是否正确?我需要“id”还是只需要两个外键“fk_recipe”和“fk_ingredient”?

第二个问题是当我在其他两个 table 中插入记录时是否可以自动填充连接点 table。还是我必须手动添加联结点中的每个关联 table?

My first question is: is it correct how I created the "recipes_ingredients" table? Do I need the "id" or I can just have the two foreign keys "fk_recipe" and "fk_ingredient"?

你的交界处 table 看起来很棒!您在 recipes_ingredients 中的 ID 将自动编号。我会将 fk_recipe 重命名为 recipe_id,将 fk_ingredient 重命名为 ingredient_id,但保持原样也完全没问题。它基于偏好。

And the second one is if it's possible to autopopulate the junction table when I insert a record in the other two tables. Or do I have to add manually every single association in the junction table?

通常,您会手动输入配料 table 中没有的配料,输入新的配方名称,最后在连接点 table 中添加条目。

但是,如果您有这样的规则:所有包含比萨这个词的食谱都将包含成分 1、2 和 3,那么您可以创建一个存储过程,其中包含逻辑以在基于 table 的联结中添加信息根据你的规则。您无法使用存储过程涵盖所有用例,因此您仍然需要前往连接点 table 并手动添加一些条目。

通常,Web 开发人员创建一个网页,允许使用网页创建食谱然后允许选择(或拖放)成分的交互。在后台,网页更新结点table.

如果交汇点 table 没有 id 栏会更好。主键应该在 (fk_recipe, fk_ingredient) 上——这应该是唯一的而不是 NULL。

您必须明确地将元素添加到联结点 table - 只是因为您添加了新配方,尚不清楚需要哪些成分。只有在特定配方需要特定成分时,交界点 table 才应该有一个条目。

结点 table 可以而且应该包括额外的数据,例如所需的成分数量。