Home >Database >Mysql Tutorial >How Can I Efficiently Query Descendants or Ancestors in a MySQL Tree Structure Without Specifying Depth?

How Can I Efficiently Query Descendants or Ancestors in a MySQL Tree Structure Without Specifying Depth?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-06 17:30:41804browse

How Can I Efficiently Query Descendants or Ancestors in a MySQL Tree Structure Without Specifying Depth?

Tree Structure Querying in MySQL: Depth-Independent Traversal

Accessing tree structure data in MySQL often involves recursive or sequential queries. However, it is possible to retrieve all descendants or ancestors of a given row in a tree-structured table without explicitly specifying the depth level using a single query. This technique known as a Modified Preorder Tree Traversal.

Query Methodology

In a tree structure table with columns id, data, and parent_id, a modified preorder traversal query can be formulated as follows:

SELECT id, data, parent_id
FROM tree_table
WHERE id IN (
    SELECT id
    FROM tree_table
    WHERE ancestry LIKE '%given_id/%'
)

Here, given_id represents the ID of the row for which you want to retrieve descendants or ancestors.

Usage and Implementation

The query string 'ancestry LIKE '%given_id/%'' filters for rows that have the given ID as part of their ancestry path. This ensures that all descendants (along with the given row) are returned. To retrieve ancestors, simply replace '%given_id/%' with '%/given_id/%'.

For example, in PHP with MySQLi:

$stmt = $mysqli->prepare("SELECT id, data, parent_id FROM tree_table WHERE id IN (SELECT id FROM tree_table WHERE ancestry LIKE '%?/%')");

Additional Information

The provided PHP example from Sitepoint (mentioned in the answer) offers a comprehensive illustration of this technique. For further insights into handling tree structures in SQL, refer to Joe Celko's "Trees and Hierarchies in SQL for Smarties."

The above is the detailed content of How Can I Efficiently Query Descendants or Ancestors in a MySQL Tree Structure Without Specifying Depth?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn