📜 ⬆️ ⬇️

The method of storing materialized paths in the database.

The main advantage of this method is access to the child nodes of any level in a single query to the database (albeit with an INNER JOIN).

Example:
necessary in the section / company / get to the list of news (item1, item2)

Data is stored in tables with the following structure:
paths - tree with paths
id
parent_id # id (paths.id)
name # ,
path # (/company/, /company/news/item1/)
title #


path_have_childs - a table of links that stores a list of child nodes with levels relative to the parent node

parent_id # id (paths.id)
child_id # id (paths.id)
level #

')
Data - table with paths:
idparent_idnamepathtitle
one0/the main
2onecompany/ company /About company
four2news/ company / news /news
fivefouritem1/ company / news / item1 /News 1
6fouritem2/ company / news / item2 /News 2
3onecatalog/ catalog /Catalog
73category1/ catalog / category1 /Category 1
eight7category2/ catalog / category1 / category2 /Category 2


The additional table is the storage of the levels of the child node relative to the parent:
parent_idchild_idlevel
one2one
oneeight3
one72
one63
onefive3
onefour2
one3one
2five2
262
2fourone
37one
3eight2
four6one
fourfiveone
7eightone

A query that generates an additional table for levels — for each node, all the child nodes are found, even those that are not directly children, and the nesting level is calculated relative to the current node:
INSERT INTO path_have_childs
SELECT
P.id AS parent_id,
C.id AS child_id,
(LENGTH(C. path ) - LENGTH(REPLACE(C. path , '/' , '' )))
- (LENGTH(P. path ) - LENGTH(REPLACE(P. path , '/' , '' )))
FROM paths AS P
INNER JOIN paths AS C ON (C. path LIKE CONCAT(P. path , '_%' ))


Select all child nodes of node X (parent_have_childs.parent_id) with level Y (parent_have_childs.level):
SELECT C. path
FROM path_have_childs AS PHC
INNER JOIN paths AS C ON (PHC.child_id = C.id)
WHERE
PHC. level = Y
AND PHC.parent_id = X


Constructive comments and criticism are welcome ...

Source: https://habr.com/ru/post/52298/


All Articles