The problem of how to handle trees in SQL has been talked about alot. The basic 3 ways are:
- store the full path for each entry
- store the parent for each node
- use nested tree
Nested tree is good for read-many-write-less applications where the tree doesn't check over time too much as a write-operation is heavy-weight most of the time.
Referencing the Parent through the full path
Using the variant of the path involves a lot of string handling and is always slow. See below:
# use a full path to each node CREATE TABLE tree_path ( node_path VARCHAR(1024) PRIMARY KEY, name VARCHAR(32) NOT NULL, INDEX (name) ) ENGINE = innodb; INSERT INTO tree_path VALUES ( '/0', 'Earth' ), ( '/0/0', 'Europe' ), ( '/0/0/1', 'Germany' ), ( '/1', 'Moon' ), ( '/0/1', 'Asia' ); # search for parent of 'Asia' SELECT t1.name FROM tree_path AS t1 WHERE t1.node_path = ( …[Read more]