What are the key components and structure of Nested Sets in PHP and MySQL?

Nested Sets is a method for storing hierarchical data in a relational database like MySQL. It involves assigning each node in the tree a left and right value, allowing for efficient querying of parent-child relationships. The key components include the left and right values, as well as the parent_id to establish the hierarchy.

// Define the structure of the nested set table
CREATE TABLE nested_set (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    lft INT NOT NULL,
    rgt INT NOT NULL,
    parent_id INT,
    FOREIGN KEY (parent_id) REFERENCES nested_set(id)
);

// Insert a root node into the nested set
INSERT INTO nested_set (name, lft, rgt) VALUES ('Root', 1, 2);

// Insert a child node under the root node
INSERT INTO nested_set (name, lft, rgt, parent_id) VALUES ('Child', 2, 3, 1);