I have Categories stored in a single table.
Where there is no limit on number of childerns.
I want to fetch all the linked categories for the provided category id:
The reason for getting the hierarchy is that I need to update the path field for each category that is either newly created or updated. I need to maintain the path field
Table name: categories
id parentId name path isLastLevel
1 0 Cat 1 Cat 1 0
2 1 Cat 2 Cat 1 > Cat 2 0
3 2 Cat 3 Cat 1 > Cat 2 > Cat 3 1
4 0 Cat A Cat A 0
5 4 Cat B Cat A > Cat B 1
Now I want to fetch all the hierarchy for id: 3
What I have tried so far is:
with recursive cte (id, name, parentId) AS (
select
id,
name,
parentId
from
categories
where
parentId = 1
union
all
select
c.id,
c.name,
c.parentId
from
categories c
inner join cte on c.parentId = cte.id
)
select
*
from
cte;
The above query returns:
[
{
id: 1,
parentId: 0,
name: Cat 1,
path: Cat 1
},
{
id: 2,
parentId: 1,
name: Cat 2,
path: Cat 1 > Cat 2
}
]
But I want this:
[
{
id: 1,
parentId: 0,
name: Cat 1,
path: Cat 1
},
{
id: 2,
parentId: 1,
name: Cat 2,
path: Cat 1 > Cat 2
},
{
id: 3,
parentId: 2,
name: Cat 3,
path: Cat 1 > Cat 2 > Cat 3
}
]
If I provide id: 2
, in that case I am expecting:
[
{
id: 1,
parentId: 0,
name: Cat 1,
path: Cat 1
},
{
id: 2,
parentId: 1,
name: Cat 2,
path: Cat 1 > Cat 2
}
]
There is something that I am doing wrong with the query, can anyone identify?
EDIT
Here is reproduced scenario: https://dbfiddle.uk/llwsSBEu
WHERE ... = 2
?