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.   

    select * from tb a,tb b where a.UpperId=b.AreaId
      

  2.   


    --上一级
    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
      

  3.   

    select tb.AreaId ,tb.AreaName from ta left join tb 
      on ta.upperId=tb.Areadid
    where ta.upperid=9
      

  4.   

    由UpperId知道8是四川select tb.AreaId ,tb.AreaName from ta left join tb  
      on ta.upperId=tb.Areadid
    where ta.upperid=8
      

  5.   

    create table tb (AreaId varchar(10), AreaName varchar(20), UpperId varchar(10))
    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