There is a table with the fields id, pid, name. Data from this table is displayed by nesting levels depending on the pid value.

If pid = 0, then this is the first level data. Further, each value of the first level is branched into subgroups of values ​​of the second level, which differ in different pid = 3, 8, 26, 32, etc.

The second level is branched into the third level, here the data is also respectively grouped by pid values.

How is such a table administered? According to what principle are the pid values ​​assigned if you need to add a new value, say, for the second or third level?

  • one
    pid most likely simply refers to the parent entry. If you have a record with pid = 3 then look, apparently its order record (from the first level) has id = 3 - Mike
  • one
    As far as I understand you about the "storage of hierarchical / tree data in the database." For example, like here . - Alex Krass
  • What is interesting is that pid does not refer to the parent record, for example, all first level records have pid = 0 and there are several such records, but the descendants of each first level record are divided into groups with different pid, - ZaurK
  • And how many subgroups do you have on the second level, more than 3x? - Mike
  • one
    It is strange if at the second level there are more than 3x, the 2nd level all refers to 3 entries of the first level. the third level with its pid already looks at the id of the second level records - Mike

1 answer 1

In your case, the pid must surely be decoded as "Parent ID". In such a tree for each child element in the pid is recorded the ID of the parent. For root elements, either 0 or null is usually specified. This tree looks like this:

Родитель1 [id=1,pid=0] -- Потомок1 [id=2,pid=1] -- Потомок2 [id=3,pid=1] ---- Потомок3 [id=4,pid=3] Родитель2 [id=5,pid=0] Родитель3 [id=6,pid=0] -- Потомок4 [id=7,pid=6] 

It is very easy to administer - while adding an element, only its parent identifier is indicated.

The conclusion is harder. Most often it is a recursive function. If we are talking about the aggregation of a large amount of data from the database, apply an artificial restriction on nesting and the corresponding number of nested queries / joins in the query elements.

There are many articles on this topic, for example: https://habrahabr.ru/post/226741/ or http://habrahabr.ru/post/46659/