How can the SQL table structure be optimized for a forum system to avoid issues with nested categories and subcategories?

To avoid issues with nested categories and subcategories in a forum system, the SQL table structure can be optimized by implementing a nested set model. This model allows for efficient querying of nested categories and subcategories without the need for recursive queries. By assigning left and right values to each category, the hierarchy can be easily navigated and manipulated.

CREATE TABLE categories (
    id INT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    parent_id INT,
    lft INT,
    rgt INT
);

INSERT INTO categories (id, name, parent_id, lft, rgt)
VALUES
(1, 'Category 1', NULL, 1, 8),
(2, 'Subcategory 1.1', 1, 2, 3),
(3, 'Subcategory 1.2', 1, 4, 5),
(4, 'Category 2', NULL, 6, 7);