AreaId AreaName UpperId
1 中国 0
2 北京 1
3 宣武区 2
4 海淀区 2
5 陕西省 1
6 西安 5
7 咸阳 5
8 四川 1
9 成都 8
求大手教下怎么由下级查询上一级,比如查成都的上一级,由UpperId知道8是四川,怎么用sql语句写啊?
1 中国 0
2 北京 1
3 宣武区 2
4 海淀区 2
5 陕西省 1
6 西安 5
7 咸阳 5
8 四川 1
9 成都 8
求大手教下怎么由下级查询上一级,比如查成都的上一级,由UpperId知道8是四川,怎么用sql语句写啊?
--上一级
declare @id int
set @id = 9select * from tb
where AreaId = (select top 1 UpperId from tb where AreaId = @id)--所有上级;with cte as
(
select * from tb where AreaId = @id
union all
select a.*
from tb a join cte b on a.AreaId = b.UpperId
)select * from cte
on ta.upperId=tb.Areadid
where ta.upperid=9
on ta.upperId=tb.Areadid
where ta.upperid=8
go
insert into tb (areaid,areaname,upperid)
select '1' ,'中国' ,'0' union all
select'2', '北京', '1'union all
select'3', '宣武区', '2'union all
select'4', '海淀区', '2'union all
select'5' ,'陕西省', '1'union all
select'6' ,'西安' ,'5'union all
select'7' ,'咸阳' ,'5'union all
select'8', '四川', '1'union all
select'9' ,'成都', '8'
-- select *from tb -- 手教下怎么由下级查询上一级,比如查成都的上一级,由UpperId知道8是四川,怎么用sql语句写啊select tb.*,bb.areaname from tb left join (select * from tb )as bb on tb.upperid=bb.areaid