【问题标题】:Trouble with data modeling/normalization数据建模/规范化问题
【发布时间】:2012-07-30 22:24:23
【问题描述】:

我正在编写一个厨房食谱脚本,但无法访问连接表中的字段。我的表设置如下:

ingredients
-----------
ingredient_id (pk)
ingredient_name (pk)
ingredient_calories (pk)

recipes
-------
recipe_id (pk)
recipe_name (pk)

meals
-----
meal_id (pk)
meal_name (pk)

recipe_has_ingredients
----------------------
recipe_id (fk)
ingredient_id (fk)

meal_has_recipes
----------------
meal_id (fk)
recipe_id (fk)

一个菜谱包含许多成分,而一顿饭包含许多菜谱。

问题是:

虽然我可以从 recipe_has_ingredients 中选择 SUM(ingredient_calories),但我不知道如何通过 meal_has_recipes 表执行此操作(以计算一餐中的总卡路里)。

非常感谢任何帮助:)

【问题讨论】:

    标签: mysql database database-design database-schema database-normalization


    【解决方案1】:

    您过度限制了事实表成分、膳食和食谱的主键。只需使用 id 字段作为 pk。

    您可以在任何名称字段上创建唯一约束。

    配方有成分表应该有recipe_id和成分_id作为复合主键。

    meal has recipes 表应该有meal_id 和recipe_id 作为复合主键。

    现在可以查询一顿饭的卡路里

     select meal_name, sum ( ingredients_calories)   from
    
        meals, meal_has_recipes, recipes_has_ingredients, recipes, ingredients
    
       where
    
          meal_name = ' good   food'   
    
          and   meal_has_recipes.meal_id =  meals.meal_id 
    
          and   meals_has_recipes.recipe_id = recipes.recipe_id
    
          and   recipes.recipe_id = recipes_has_ingredients.recipe_id
    
          and    ingredients.ingredients_id = recipes_has_ingredients.ingredients_id;
    

    【讨论】:

      猜你喜欢
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 2016-05-27
      • 2011-03-03
      相关资源
      最近更新 更多