查找ron的所有上级,mdrig表示上级的empid
create table employees(empid int , mgrid int , name varchar(10))
insert into employees values('1' , null , 'nancy')
insert into employees values('2' , '1' , 'andrew')
insert into employees values('3' , '1' , 'janet')
insert into employees values('4' , '1' , 'joe')
insert into employees values('5' , '2' , 'steven')
insert into employees values('6' , '2' , 'mach')
insert into employees values('7' , '3' , 'rouh')
insert into employees values('8' , '3' , 'laura')
insert into employees values('9' , '3' , 'anna')
insert into employees values('10' , '4' , 'lili')
insert into employees values('11' , '7' , 'davy')
insert into employees values('12' , '7' , 'ron')
insert into employees values('13' , '11' , 'danna')
select * from employees where empid =(select mgrid from employees where name='ron'
就事论事型,不使用递归实现
1、with cte as(
select a.name as 上级,b.name as 下级 from employees a ,employees b where a.empid=b.mgrid
)
select a.下级 as ron,a.上级 上级1,b.上级 上级2 from cte a,cte b where a.上级=b.下级 and a.下级='ron'
cte递归实现
2、with maco as
(
select * from employees where name ='ron'
union all
select a.* from employees a,maco b where a.empid =b.mgrid )
select * from maco order by empid
cte递归用法:
WITH cte_name ( column_name [,...n] )
AS
(
CTE_query_definition –- Anchor member is defined. //select * from employees where name ='ron'
UNION ALL
CTE_query_definition –- Recursive member is defined referencing cte_name. //select a.* from employees a,maco b where a.empid =b.mgrid 包含cet本身
)