skip to Main Content

How can I use the value from one query into the second one. I tried with an alias "papa" but I read that the order of executions makes the alias not available to the second query.

What would be the appropriate way of achieving something like below ?

select id, name, parent_id as papa, (select name from people where id = papa)
from people;

2

Answers


  1. Make the alias earlier

    select id, name, papa, (select name from people where id = papa)
    from (select id, name, parent_id as papa people);
    
    Login or Signup to reply.
  2. I would use a self join for this:

    select p.id, 
           p.name, 
           p.parent_id as papa_id,
           papa.name as papa_name
    from people p
      left join people papa on p.parent_id = papa.id
    

    Online example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search