日期:2014-05-18  浏览次数:20517 次

一个让我困惑的sql查询,求高手
AreaId AreaName UpperId
1 中国 0
2 北京 1
3 宣武区 2
4 海淀区 2
5 陕西省 1
6 西安 5
7 咸阳 5
8 四川 1
9 成都 8


求大手教下怎么由下级查询上一级,比如查成都的上一级,由UpperId知道8是四川,怎么用sql语句写啊?

------解决方案--------------------
select * from tb a,tb b where a.UpperId=b.AreaId
------解决方案--------------------
SQL code

--上一级
declare @id int
set @id = 9

select * 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