id parentid Name
1 NULL 汽车租赁有限公司
2 1 安吉租赁
3 2 华东地区
4 3 上海地区
5 4 上海分公司
6 5 上海门店1
7 5 上海门店2
8 5 上海门店3
9 5 上海门店4
10 5 上海门店5
11 5 上海门店6
12 5 上海门店7根据id查询出其上级所有的id
比如说:id=7 我要查询结果为1,2,3,4,5
id=4 我要查询结果为1,2,3
1 NULL 汽车租赁有限公司
2 1 安吉租赁
3 2 华东地区
4 3 上海地区
5 4 上海分公司
6 5 上海门店1
7 5 上海门店2
8 5 上海门店3
9 5 上海门店4
10 5 上海门店5
11 5 上海门店6
12 5 上海门店7根据id查询出其上级所有的id
比如说:id=7 我要查询结果为1,2,3,4,5
id=4 我要查询结果为1,2,3
insert into @T(cid,pid,nm)
select 0,null,'上海'
union
select 1,0,'嘉定'
union
select 2,0,'长宁'
union
select 3,0,'黄浦'
union
select 4,0,'青浦'
union
select 5,0,'宝山'
union
select 6,0,'徐汇'
union
select 7,1,'安亭'
union
select 8,1,'黄渡'
union
select 9,1,'江桥'
union
select 10,5,'桃浦';with tb(cid,pid,nm,lv)
as
(
select cid,pid,nm,lv=0 from @T where cid=9
union all
select a.cid,a.pid,a.nm,b.lv+1 from @T a,tb b where b.pid=a.cid
)
select * from tb
select tb.id,
from tb
where tb.id in (select parentid
from tb t1
where tb.id = t1.parentid
and id < 7
)