Search code examples
sqlrecursive-query

How do I generate a recursive query to get information from two tables


I have a request to get all child records

with recursive cte (id, parentId) as 
(
    select id, parentId 
    from users 
    where id = 1 

    union all 

    select p.id, p.parentId 
    from users p 
    inner join cte on p.parentId = cte.id 
) 
select * from cte

there is also a user_info table

id, userId, login

I need to query here for more information. How can i do this?
I tried adding an extra inner join, but it didn't work.


Solution

  • You can just join that second table at the end:

    with recursive cte (id, parentId) as (
        select     id,
                   parentId
        from       users
        where      id = 1
    
        union all
    
        select     p.id,
                   p.parentId 
        from       users p 
        inner join cte 
                on p.parentId = cte.id 
    ) 
    select    * 
    from      cte
    left join user_info 
           on userId = cte.id