I have a tree encoded in the MySQL database as edges:
CREATE TABLE items ( num INT, tot INT, PRIMARY KEY (num) ); CREATE TABLE tree ( orig INT, term INT FOREIGN KEY (orig,term) REFERENCES items (num,num) )
For each sheet in the items.tot tree, items.tot set by someone. For internal items.tot nodes should be the sum of his children. Repeated execution of the following query will create the desired result.
UPDATE items SET tot = ( SELECT SUM(b.tot) FROM tree JOIN items AS b ON tree.term = b.num WHERE tree.orig=items.num) WHERE EXISTS (SELECT * FROM tree WHERE orig=items.num)
(note that this does not actually work, but as for the point)
Suppose a database exists and the invariant is already running.
The question arises:
What is the most practical way to update the database while maintaining this requirement? Updates can move nodes around or change the tot value on leaf nodes. It can be assumed that leaf nodes will remain as leaf nodes, internal nodes will remain internal nodes, and all this will remain as a regular tree.
Some thoughts that I had:
- Complete cancellation, after any update, recount everything (Um ... No)
- Set a trigger in the item table to update the parent of any updated row
- It will be recursive (updates of update triggers, update trigger ...)
- Doesn't work, MySQL cannot update the table that started the trigger
- Set a trigger to schedule the update of the parent of any updated row
- It will be iterative (get an element from the graph, process it with a schedule of more elements).
- What does it mean? Trust the client code to get it right?
- The advantage is that with proper ordering of updates, fewer amounts should be a computer. But this ordering is complexity and its own.
An ideal solution would generalize to other "aggregate invariants"
FWIW I know this is βa little overboardβ, but I do it for fun (Fun: verb, search for the impossible, doing it. :-)
algorithm mysql data-structures invariants
BCS
source share