Store and traverse hierarchies in SQL
Modeling and retrieving hierarchical information in databases is critical for many applications. One popular method is the modified preorder traversal algorithm (MPTT).
MPTT algorithm
MPTT organizes hierarchical data in a single table, with three columns per node:
-
ID: The unique identifier of the node.
-
Left: Index of the leftmost node in the node subtree.
-
Right: The index of the rightmost node in the node subtree.
Insert into tree
To insert a new child node into the tree, we need:
- Find the Right value of the parent node.
- Sets the child node’s Right value to the parent node’s Right 1.
- Sets the parent node’s Right value to the parent node’s Right 2.
- Sets the child node’s Left value to the parent node’s Right - 1.
Traverse the tree
MPTT allows easy tree traversal using explicit SQL queries:
-
Get all child nodes of a node: SELECT * FROM table WHERE Left BETWEEN parent.Left AND parent.Right
-
Get all descendants of a node: SELECT * FROM table WHERE Left > parent.Left AND Right < parent.Right
- Get all ancestors of a node: SELECT * FROM table WHERE Left < node.Left AND Right > node.Right
Other modeling methods
In addition to MPTT, other methods of storing hierarchies include:
-
Adjacency list model: Use two tables to represent the hierarchy, one table containing parent-child relationships and the other table containing additional node data.
-
Figure: Models hierarchies as nodes connected by edges, providing complex join and query flexibility.
Class Library
Various libraries simplify working with MPTT and other hierarchical data structures in programming languages like PHP and Java:
- PEAR::Tree
- Doctrine ORM
- Hibernate
The above is the detailed content of How Can MPTT Algorithm Efficiently Store and Navigate Hierarchical Data in SQL?. For more information, please follow other related articles on the PHP Chinese website!