Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a recursive join to get the lowest level of data with TSQL

I have the following set of data:

ID          ParentID 
----------- ---------
8320        NULL     
8321        8320     
8322        8320     
8323        8322     
8325        NULL     
8328        8325     
8329        8328 

What I am trying to achieve is to select all the rows that belongs to a specific ID. For instance, if I am querying ID = 8320, the following data must be returned:

ID          ParentID 
----------- ---------
8320        NULL     
8321        8320     
8322        8320     
8323        8322

So far this is what I have attempted with no real success.

select *
from JobQueueLog JQL
    left join JobQueueLog JQLC on
        JQL.ID = JQLC.ParentID
    and JQLC.ParentID is not null
where JQL.ID = 8320

Any help please?

like image 295
Rudolf Lamprecht Avatar asked Nov 20 '25 09:11

Rudolf Lamprecht


1 Answers

You need to use a CTE and make a recursive query

with tmp (id, parentid) as (
select id, parentid
from rec
where id = 8320
union all
select rec.id, rec.parentid
from tmp
inner join rec on tmp.id = rec.parentid
)
select id, parentid
from tmp
like image 125
Nemeros Avatar answered Nov 22 '25 23:11

Nemeros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!