Skip to content
Advertisement

How to set nested path values in the tree structure?

In our database, a tree structure is implemented like this:

I need to set the path’s values so that rows where pos_level is 2 would read like this: folder1/file1, folder1/file2, folder1/file3. So I need an SQL query which would take the name of the “parent” folder (but no parent_id is used in our system, only pos_left, pos_right, pos_level) concatenated with “/” and then with the entity’s name.

I already have the simple stuff:

And I need this:

Thank you!

Advertisement

Answer

Since you are using older version of MySQL recursion is out of scope. I have used self join to get the result you want. Please use your table name instead of treestructure in the query:

Schema and insert statements:

Update query:

Select Query:

Output after update:

name path pos_left pos_right pos_level
folder1 folder1 207 214 1
file1 folder1/file1 208 209 2
file2 folder1/file2 210 211 2
file3 folder1/file3 212 213 2

db<>fiddle here

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement