Home > Mobile >  Use value from one query into the second one
Use value from one query into the second one

Time:12-01

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;

CodePudding user response:

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

CodePudding user response:

Make the alias earlier

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