table 中字段数量可变的数据库

Database with variable number of fields in a table

注意:此为个人自学项目,不涉及工作或学习。

我是 creating/databases 的新手,我正在寻找如何设计最符合逻辑的 table 关系的见解。

提供一些背景信息:我想设计一个数据库来保存不同的酒精饮料,如鸡尾酒、啤酒、葡萄酒等。数据库将包含饮料 ID、名称、描述等字段,最后是配料。

我遇到的问题是试图围绕饮料成分数量可变的逻辑进行思考。例如,一种鸡尾酒可能只有 2 种成分,而另一种可能有 4、5、6 种,等等。

到目前为止,我已经创建了这个设计(从我的角度来看,它在逻辑上并不合理,并且一直在试图找出存储信息的最佳方式)。

**Drinks table**

Drink ID

Drink name

Drink description

Drink category     // Beer, Cocktails, 

Drink type    // Pale ale, Lager, etc.

**Cocktails Table**

Drink ID

Drink instructions

**Beers Table**

Drink ID

**Ingredients Table**

Ingredient id

Ingredient name

非常感谢您提供的任何见解,谢谢。

删除鸡尾酒和啤酒 tables。这些只是不同的饮料,您可以将 "Instructions" 字段添加到鸡尾酒的饮料 table 中。 Ingedients table 是处理食材的正确方式。我只是一个用于数量的数字字段和一个用于测量的文本字段(即:2 盎司)

如果您想将鸡尾酒定义为成分列表,您需要一个 Ingredient table 来描述您的成分,以及一个 CocktailIngredient "cross-table"鸡尾酒需要多少每种成分:

Ingredient table:

id name
-- ------
1  vodka
2  Kahlua
3  Cream
...

Cocktail table:

id  name
--  -------------
 1  Black Russian
 2  White Russian

现在是最有趣的部分,CocktailIngredient table:

c_id i_id parts
---- ---- -----
   1    1     5
   1    2     2
   2    1     5
   2    2     2
   2    3     3

最后一个 table 表示 "Black Russian" (c_id = 1) 需要五份伏特加 (i_id=1) 和两份 Kahlua (i_id = 2) .

注:如果你能从上面的table中算出"White Russian"的比例,你就理解了many-to-many的解法。

我会选择:

**Drinks table**
   ID
   name
   description
   category_id    //foreign key to a category table 
   type_id        //foreign key to a type table

**Category** //Beer, Cocktails, etc
   ID
   Name

**Type** //Pale ale, Lager, etc.
   ID
   Name

**Ingredients** //Hold all ingredients
   Id
   description

**Category_Ingredients** //That category has ingredients
   category_id
   Ingredient_id
   amount //if you want be perfectionist

这将使您拥有明确定义的数据。您可以专门制作饮料,例如,如果客户喜欢某种特定成分,您可以在饮料成分中添加 table,例如:

 **Drink_ingredient**
    id_drink
    id_ingredient
    amount