如何在 SQL 数据库中组织有关菜肴的信息?

How to organize information about dishes in a SQL database?

我将创建一个 SQL 数据库来存储有关烹饪的信息。会有菜肴、配料等

问题是如何表示一道菜的信息,以便包含与这道菜相关的所有成分。

例如,有一个 table 的成分包含以下字段:
- id
- ing_name
- ing_type
...
等等

另一个 table 包含有关菜肴的信息,例如:
- id
- dish_name
- dish_type
...
- 等等

而且diss相关的食材一定要有,但是数量可以不一样,所以我不知道table里面的菜品相关的食材怎么存。

假设 id = 1 的菜肴包含 id = 3、5、8 和 12 的成分,我如何在关于菜肴的 table 中表示此信息?

您刚刚发现了多对多关系!

您需要 3 table 秒来处理这些数据,"Dish"、"Ingredient" 和 "DishIngredient"。 "DishIngredient" 有时称为 "Junction table"。它存储有关其他 2 table 之间关系的信息。

您的 table 结构将如下所示:

  • 菜肴
    • 菜品编号
    • 姓名
  • 成分
    • 成分ID
    • 姓名
  • 菜肴成分
    • 菜品编号
    • 成分ID
    • 数量

您希望 Dish.DishIDIngredient.IngredientID 为主键,DishIngredient 中有外键。 DishIngredient 上的主键应该是 DishIngredient.DishID 和 DishIngredient.IngredientID.

上的复合键

DishIngredient 上的主键设为组合键并不是绝对必要的,它可以有自己的 ID,但组合主键将防止同一成分多次出现在同一道菜中。

您可以将这些 table 与联接连接起来,以获取食谱的所有成分,如下所示:

SELECT 
    Dish.Name AS Dish, 
    Ingredient.Name AS Ingredient, 
    DishIngredient.Quantity AS Quantity
FROM Dish
INNER JOIN DishIngredient 
    ON Dish.DishID = DishIngredient.DishID
INNER JOIN Ingredient 
    ON DishIngredient.IngredientID = Ingredient.IngredientID
WHERE Dish.Name ='Pizza'