Tree data structure storage method (query)
Adjacency list model
In daily business development, we often encounter some tree-like data with a hierarchical structure. When stored in a relational database, this data structure is often stored in a model called an adjacency list, like this:
CREATE TABLE `categories` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` char(100) NOT NULL, `pid` int(11) DEFAULT 0, PRIMARY KEY (`id`) ) ENGINE=InnoDB;
This model represents The picture shows:
# I believe many people are already familiar with this data model, so I won’t go into too much detail here. Let’s focus on the following data model
Nested set model
Another way to represent a tree is to store it as a set. We redefine the following table structure:
CREATE TABLE `categories` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` char(100) NOT NULL, `lft` int(11) NOT NULL UNIQUE CHECK (lft> 0), `rgt` int(11) NOT NULL UNIQUE CHECK (rgt> 1), PRIMARY KEY (`id`) ) ENGINE=InnoDB;
And the diagram of this model will look like the following:
lft and rgt is used as the boundary of the set. The greater the difference between the two, the larger the set and the more elements in it.
According to the subset, find the parent category
SELECT c2.* FROM categories as c1, categories as c2 WHERE c1.lft BETWEEN c2.lft and c2.rgt AND c1.title = '华为'; +----+-------------+-----+-----+ | id | title | lft | rgt | +----+-------------+-----+-----+ | 1 | Smartphones | 1 | 14 | | 5 | Harmony OS | 10 | 13 | | 8 | 华为 | 11 | 12 | +----+-------------+-----+-----+
According to the parent, find all the subsets under it
SELECT c1.* FROM categories AS c1, categories AS c2 WHERE c1.lft BETWEEN c2.lft AND c2.rgt AND c2.title = 'Smartphones'; +----+-------------+-----+-----+ | id | title | lft | rgt | +----+-------------+-----+-----+ | 1 | Smartphones | 1 | 14 | | 3 | Android | 2 | 5 | | 4 | iOS | 6 | 9 | | 5 | Harmony OS | 10 | 13 | | 6 | 小米 | 3 | 4 | | 7 | iPhone | 7 | 8 | | 8 | 华为 | 11 | 12 | +----+-------------+-----+-----+
View the level of each category
SELECT COUNT(c2.id) AS indentation, c1.title FROM categories AS c1, categories AS c2下周三we'fv WHERE c1.lft BETWEEN c2.lft AND c2.rgt GROUP BY c1.title ORDER BY c1.lft; +-------------+-------------+ | indentation | title | +-------------+-------------+ | 1 | Smartphones | | 2 | Android | | 3 | 小米 | | 2 | iOS | | 3 | iPhone | | 2 | Harmony OS | | 3 | 华为 | +-------------+-------------+
Advantages and Disadvantages
Adjacency List Model
The adjacency list model is easy to understand, and the code we need is also very simple.
But in most programming languages, it is slow and inefficient. This is mostly caused by recursion. We need to do a database query for each node in the tree.
This can make the function very slow when dealing with large trees since each query takes some time. Because for each function, a recursive algorithm is needed to obtain the number.
Of course, if you use a recursive-friendly language like List, you can ignore the shortcomings of this data model. But for PHP, it will make the entire processing of this data model extremely slow.
Nested set model
Compared with the adjacency list model, this data model is obviously not so easy to understand. And it cannot be so simple to add data. It needs to calculate the values on the left and right sides when adding, and move the subsequent values, which increases the pressure of adding data.
Similarly, the benefit it brings is that it allows you to complete a tree query with a simple query, and you can calculate how many sub-elements it has based on the two parameters lft and rgt.
Summary
Both models have their own advantages and disadvantages, one is better than insertion and the other is better than query. Although I prefer the nested set model, it still needs to be chosen based on the specific business.
The above is the detailed content of Tree data structure storage method (query). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



When using complex data structures in Java, Comparator is used to provide a flexible comparison mechanism. Specific steps include: defining the comparator class, rewriting the compare method to define the comparison logic. Create a comparator instance. Use the Collections.sort method, passing in the collection and comparator instances.

Data structures and algorithms are the basis of Java development. This article deeply explores the key data structures (such as arrays, linked lists, trees, etc.) and algorithms (such as sorting, search, graph algorithms, etc.) in Java. These structures are illustrated through practical examples, including using arrays to store scores, linked lists to manage shopping lists, stacks to implement recursion, queues to synchronize threads, and trees and hash tables for fast search and authentication. Understanding these concepts allows you to write efficient and maintainable Java code.

Reference types are a special data type in the Go language. Their values do not directly store the data itself, but the address of the stored data. In the Go language, reference types include slices, maps, channels, and pointers. A deep understanding of reference types is crucial to understanding the memory management and data transfer methods of the Go language. This article will combine specific code examples to introduce the characteristics and usage of reference types in Go language. 1. Slices Slices are one of the most commonly used reference types in the Go language.

AVL tree is a balanced binary search tree that ensures fast and efficient data operations. To achieve balance, it performs left- and right-turn operations, adjusting subtrees that violate balance. AVL trees utilize height balancing to ensure that the height of the tree is always small relative to the number of nodes, thereby achieving logarithmic time complexity (O(logn)) search operations and maintaining the efficiency of the data structure even on large data sets.

Overview of Java Collection Framework The Java collection framework is an important part of the Java programming language. It provides a series of container class libraries that can store and manage data. These container class libraries have different data structures to meet the data storage and processing needs in different scenarios. The advantage of the collection framework is that it provides a unified interface, allowing developers to operate different container class libraries in the same way, thereby reducing the difficulty of development. Data structures of the Java collection framework The Java collection framework contains a variety of data structures, each of which has its own unique characteristics and applicable scenarios. The following are several common Java collection framework data structures: 1. List: List is an ordered collection that allows elements to be repeated. Li

Overview of the PHPSPL Data Structure Library The PHPSPL (Standard PHP Library) data structure library contains a set of classes and interfaces for storing and manipulating various data structures. These data structures include arrays, linked lists, stacks, queues, and sets, each of which provides a specific set of methods and properties for manipulating data. Arrays In PHP, an array is an ordered collection that stores a sequence of elements. The SPL array class provides enhanced functions for native PHP arrays, including sorting, filtering, and mapping. Here is an example of using the SPL array class: useSplArrayObject;$array=newArrayObject(["foo","bar","baz"]);$array

The hash table can be used to optimize PHP array intersection and union calculations, reducing the time complexity from O(n*m) to O(n+m). The specific steps are as follows: Use a hash table to map the elements of the first array to a Boolean value to quickly find whether the element in the second array exists and improve the efficiency of intersection calculation. Use a hash table to mark the elements of the first array as existing, and then add the elements of the second array one by one, ignoring existing elements to improve the efficiency of union calculations.

In-depth study of the mysteries of Go language data structure requires specific code examples. As a concise and efficient programming language, Go language also shows its unique charm in processing data structures. Data structure is a basic concept in computer science, which aims to organize and manage data so that it can be accessed and manipulated more efficiently. By in-depth learning the mysteries of Go language data structure, we can better understand how data is stored and operated, thereby improving programming efficiency and code quality. 1. Array Array is one of the simplest data structures
