select a.id, (case
when count(a.p_id)=0 then 'Root'
when count(b.id)=0 then 'Leaf'
else 'Inner' end) Type
from tree a left join tree b on a.id=b.p_id
group by 1
order by 1
子查询
select id,
case
when p_id is null then 'Root'
when id in (select p_id from tree) then 'Inner'
else 'Leaf' end Type
from tree
order by 1