I am building a navigation menu from a list of pages.
The table is like this:
Table name: pages
id | type | parent | name
-------------------------------
1, 1, null, root1
2, 1, null, root2
3, 2, 2, home
4, 2, 3, child
5, 2, 4, sub_child
6, 3, 5, sub_sub_child
type:
1 = root page / site
2 = page
3 = ...
My problem is that from any page, I have to find the root page.
I have a column parent that refers to the parent page, except for the root pages.
I can have multiple root pages in the table, but each page has only one parent.
Could somebody help me to write a recursive query ?
I’m trying to use this query, but it doesn’t work:
with recursive pages (id, parent) as
(
select pages.id,
pages.parent,
from pages
where pages.id = 4
union all
select pages.id,
pages.parent,
from pages
inner join pages p on p.id = pages.parent
)
select id
from pages;
Thanks
My farovite trick to handle tree structured data in database is add a column
FullIDto table to avoid complex (parhaps recursive) SQLs/Stored Procedures.So, to find the root page id, just extract the first part of
FullIDvia SQL or your application language.If using SQL, you can use the following SQL to get the root id.
To delete a node and it’s children
To move a node and it’s children
Note
This trick is only applied on limited tree level cases, or the
FullIDcan’t hold long content if tree level is too deep.