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