I have a complex (and perhaps interesting) SQL question for you all:
Let's say I have an INGREDIENT table for recipes, that looks something
like this:
INGREDIENT
id primary key,
name varchar(200),
carbohydrates_g number
Ingredients can also be composed of several other ingredients. For
example, let's say you have a pancake mix that is composed of flour,
eggs, and salt.
MIX
master_ingredient references INGREDIENT,
component_ingredient references INGREDIENT,
percent number
Thus, an entry for this pancake mix would be in INGREDIENT:
id 5
name "pancake mix"
carbohydrates 0
The pancake mix has three components, so there are three entries in
the MIX table:
master_ingredient 5
component_ingredient 3 (let's say three is water)
percent 33 (let's say the mix is 33% water)
master_ingredient 5
component_ingredient 2 (let's say two is flour)
percent 20 (let's say the mix is 20% flour)
master_ingredient 5
component_ingredient 1 (let's say one is salt)
percent 47 (let's say the mix is 47% salt)
It's not terribly difficult to figure out what the total carbohydrate
content for this pancake mix is, but what if a mix contains another
mix? It becomes a recursive endeavor.
I could do this with Tcl, and just sum everything up, but I imagine a
better solution might be found using SQL, and perhaps using CONNECT
BY. I've never used it for summing things up in a tree before, however.
Sql for Smarties has a section that discusses this. In his
example, you have parts for a machine. Each of the parts is composed
of component parts, and the weight of the part is based on the sum of
the weight of the components. He figures it out iteratively, by going
through a table and saying component A's weight = sum of all child
components. It doesn't really seem very ideal.
Has anybody encountered this issue before, and solved it satisfactorily?