2

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:

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: 2 i.e Cat 2

Expected response:

[
    {
        id: 1,
        parentId: 0,
        name: Cat 1,
        path: Cat 1,
        isLastLevel: 0
    },
    {
        id: 2,
        parentId: 1,
        name: Cat 2,
        path: Cat 1 > Cat 2,
        isLastLevel: 0
    },
    {
        id: 3,
        parentId: 2,
        name: Cat 3,
        path: Cat 1 > Cat 2 > Cat 3,
        isLastLevel: 1
    }
]

I am trying this query but its not giving me the parent records:

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;

I have also created an SQL playground:

http://sqlfiddle.com/#!9/43862d

StormTrooper
  • 1,731
  • 4
  • 23
  • 37
  • 2
    If the path of Cat 3 contains Cat 2 then the parent of Cat 3 should also be Cat 2, not Cat 1. – Arjan Nov 11 '22 at 12:10
  • Yes thats my mistake, let me correct this in the question – StormTrooper Nov 11 '22 at 12:11
  • You do not necessarily need a recursion, since the path is encoded in a field. – Shadow Nov 11 '22 at 12:17
  • @Shadow Actually I need it for updating path field, – StormTrooper Nov 11 '22 at 12:20
  • Well, then use the recursive solutions proposed in the duplicate question. Added a second duplicate to explicitly show down and up traversal. – Shadow Nov 11 '22 at 12:33
  • @Shadow I tried this solution, but for some reason it is not returning any result – StormTrooper Nov 11 '22 at 12:38
  • @Shadow you can see I am trying to the same solution in this sqlfiddle: http://sqlfiddle.com/#!9/23403a/3 – StormTrooper Nov 11 '22 at 12:39
  • Then you have asked the wrong question! You asked how to do it - that's a dupicate question. If you already know how you are supposed to do, but get stuck with it, then you should have included the reference to the original code and include the code in your question along with exact error message or description of the unexpected behaviour. – Shadow Nov 11 '22 at 13:10
  • ok let me update the question here, cant you re-open it after? – StormTrooper Nov 11 '22 at 13:11
  • @Shadow Please check the updated question and re-open it, thanks – StormTrooper Nov 11 '22 at 13:47

0 Answers0