2012-03-27 148 views
6

这是一个后续行动,我的问题在这里:
How to implement a many-to-many hierarchical structure in MySQL
这里:
How to record sequential collections of records in MySQL如何将排序顺序添加到表示多对多关系的MySQL关闭表中?

总之,我想在MySQL中实现配方表和其他指令。配方是连续的一系列指令或其他配方。例如,您可以想象一个Peach_preserve配方,以及一个使用Peach_preservePeach_tart,以及一系列其他步骤(说明)。 Peach_preserve可用于许多其他食谱。

我读this blog post by Bill Karwin about closure tables,我觉得这个解决方案最好的解决我的难题(我的层次是许多一对多和步骤是连续的)。因此,例如我会有:

recipe 
id name 
1 Peach preserve 
2 Cubed peeled peaches 
3 Fresh peaches 
4 Powdered sugar 
5 Cook together 
6 Peel and cut in chunks 
7 Mix 

step (or instruction) 
id desc 
1 Cook together 
2 Buy peaches 
3 Buy sugar 
4 Peel and cut in chunks 
5 Mix 

recipe_instruction 
(Ancestor) (Descendant) 
recipe_id step_id depth descendant_is_instruction 
3   3   0  0 
3   2   1  1 
4   4   0  0 
4   3   1  1 
6   6   0  0 
6   4   1  1 
2   2   0  0 
2   3   1  0 
2   2   2  1 
2   6   1  0 
2   4   2  1 
(and so on...) 

我不是descendant_is_instruction标志的粉丝,但我不知道该怎么做。我想我可以用一个descendant_is_leaf取代它,以确定终端项目......

的排序顺序是由包含在深度为1的所有关系的表表示:

Depth=1 table 
recipe_id step_id  order 
3   2   1 
4   3   1 
6   4   1 
2   3   1 
2   6   2 

我简化这里因为在实践中我会分开成分和指示,但你明白了。

所以,是一个很好的方式既分层数据结构和工序顺序的概念结合起来?我应该做什么来改进/简化?

回答

0

因此,我对我的问题做了一些研究,主要利用Bill Karwin在这里和其他地方提供的信息(我最终决定购买他的书)。基于此,我认为最好的选择是在我的关闭表中添加一个面包屑列,类似于Bill在这里推荐的MySQL Closure Table hierarchical database - How to pull information out in the correct order

面包屑会让我ORDER BY,这将解决我的订购问题。

我会通过查询闭包表来查找终端节点,查找除自身以外没有其他祖先的所有节点。

0

我可能会在这里下车的方式,但配方和指令可能是同一个表,简化您的关系。

指令:ID,姓名,is_recipe

步骤:PARENT_ID,child_id,为了

现在配方能有说明和食谱的孩子。一个指令,甚至可以遵循食谱但减少黄油......

您可能需要尽管添加一些循环控制...

8

配方是一系列连续的指令或其他配方。

取决于如何一个读的那句话,这可能是不明确的。

如何:

配方是一系列顺序指令。

的指令要么简单(叶)或络合物(使用另一配方)。

其中给出:

Table recipe: 
- column id 
- column name 
- column total_cost, total_preparation_time, etc 

Table instruction: 
- column id 
- column recipe_id 
- column step_order 
- column description 
- column child_recipe_id (can be NULL) 

所以,如果桃挞使用面团和桃保留:

select * from recipe order by id; 
id  name 
1  Dough 
2  Peach preserve 
3  Peach tart 

select * from instruction order by recipe_id, step_order; 
id recipe_id step_order description  child_recipe_id 

100  1  1  Get flour  NULL 
101  1  2  Add water  NULL 
102  1  3  Mix together NULL 

201  2  1  Peel peaches NULL 
202  2  2  Cube peaches NULL 
203  2  3  Add sugar  NULL 
204  2  4  Cook together NULL 

301  3  1  Pre heat oven NULL 
302  3  2  Prepare dough 1 
303  3  3  Prepare peach 2 
304  3  4  Bake   NULL 

有没有 “是叶” 标志。

指令是一个叶子,如果它不指向子配方,即child_recipe_id为NULL。

+0

从这个意义上说,'description'/'name'字段是相互冗余的。如何让一张桌子拥有食谱树,另一张桌子只是名字? – Yuval 2012-04-06 12:05:49

+0

@Yuval,我没有看到配方名称和使用配方冗余的说明描述。前者描述了由此产生的成分是什么(例如,“融化的巧克力”),后来的“如何”使用了结果(例如,“用融化的巧克力在平板上绘画”)。 Yumm。 – 2012-04-06 12:46:36