sql - 根据id获取父值

时间:2012-03-11 16:53:52

标签: sql

我有一个名为employee

的表

员工表字段和样本值

--------------------------------
id      name     parentid
--------------------------------
1       suresh    null
--------------------------------
2       ram       1
--------------------------------
3       ravi      2
--------------------------------
4       raju      3
--------------------------------

这里我需要获取给定id值的current,parent和grand parent值的name字段值。我需要输出如下

假设输入id为4,那么我的预期输出为

name    parentName    grandParentName
-----------------------------------------
raju    ravi           ram
-----------------------------------------

如何为此编写查询?

2 个答案:

答案 0 :(得分:3)

这里你去..

select e1.name, e2.name as parentName, e3.name as grandParentName
from employee e1
left join employee e2 on e1.parentId = e2.id
left join employee e3 on e2.parentId = e3.id

where e1.id = 4

答案 1 :(得分:0)

好问题!这是经过测试和运作的。

select my.`name`, p.`name` as 'parent name', gp.`name` as 'grandparent name'
from employee my 
left outer join employee p on p.id=my.parentid 
left outer join employee gp on gp.id = p.parentid
where my.`id`=4