【发布时间】:2017-02-15 17:02:11
【问题描述】:
很抱歉,我无法在标题中创建更具体的问题;这可能是由于我对术语不熟悉。
这是我正在使用的 MySQL 数据库部分的简化图:
示例数据可能是:
- 食谱:“苹果派”
- recipeIngredientItem:“3 杯 + 2 汤匙通用面粉”
- recipeStep:“将烤箱预热至 400°F”
- 成分:“通用面粉”
- compoundMeasurement:“3 杯 + 2 汤匙”
- simpleMeasurement:“3 杯”
- measurementUnit:“杯子”
如果我删除一个食谱,我不是要级联并删除所有相关的 recipeIngredientItems 和 recipeSteps。但是,有一些并发症:
- 如果删除了 recipeIngredientItem,我希望删除关联的 compoundMeasurement,然后再删除与该 关联的所有 simpleMeasurement >复合测量。但我不想删除相关的 ingredient 和 measurementUnit。
- 我不确定当 ingredient 或 measurementUnit 被删除时我想做什么,但我认为我的 UI 会警告用户并进行适当处理 ("警告!如果您删除成分“通用面粉”,它将从所有使用它的食谱中删除。”)。
- 另外,我的意图是以其他方式使用 compoundMeasurement,例如与 pantryItem 表关联来管理库存。所以在 compoundMeasurement 中有一个“recipeIngredientItem”键列是没有意义的。但是,如果这是一个糟糕的设计,我可以有单独的 recipeCompoundMeasurement 和 pantryItemCompoundMeasurement 表。这似乎是一个不必要的复杂化,但这很可能反映了我业余的自学数据库知识。 :)
我应该如何为这些表设置外键约束?还是以某种方式重新设计数据库会更好?
编辑:
对于它的价值,这是我迄今为止所做的工作(就约束而言),但我不确定它是否是最优雅的解决方案。所有约束都设置为在删除或更改时级联:
recipeIngredientItem.amount: links to compoundMeasurement.idNumber
recipeIngredientItem.ingredient: links to ingredient.idNumber
recipeIngredientItem.recipe: links to recipe.idNumber
recipeStep.recipe: links to recipe.idNumber
simpleMeasurement.measurementUnit: links to measurementUnit.idNumber
simpleMeasurement.compoundMeasurement: links to compoundMeasurement.idNumber
有了这些,当我删除一个 recipe 时,相关的 recipeIngredientItems 和 recipeSteps 将被删除,但我需要去通过并明确删除与已删除的 recipeIngredientItem 关联的 compoundMeasurement(这反过来又删除了关联的 measurement)。当然,这很容易做到,只是有点不雅。但也许这就是以多种方式使用 compoundMeasurement 的成本......
【问题讨论】:
标签: mysql foreign-keys innodb foreign-key-relationship