表结构: t_test
treeid               personid                    pid
00010002             002                         001
000100020003         003                         002
000100020004         004                         002
00010002000030001    005                         003比如select * from t_test where pid='002' 得到的是002中的子记录
现在怎么得到002子记录中有子记录的呢?
如上结果就只得到personid=003这条记录.而004就不是,因为它没有子记录.
急啊..帮帮我.`!!!!!!!

解决方案 »

  1.   

    select * from t_test a
    where pid='002' 
    and exists (
    select 1 from t_test 
    where pid=a.personid
    )
      

  2.   

    Select * From  t_test  Where pid in
    (
    Select personId From t_test Where pid = '002'
    )
      

  3.   


    create table tb
    (
    personid char(3),
    pid char(3)
    )insert tb 
    select '002','001' union all
    select '003','002' union all
    select '004','002' union all
    select '005','003' 
    gocreate proc getChildren(@personid char(3))
    as
    create table #temp
    (
    personid char(3),
    pid char(3),
    leve int
    )declare @Level int
    set @Level=0insert  #temp
    select personid,pid,@Level from tb where personid=@personidwhile @@rowcount>0
    begin
    set @Level=@Level+1 insert  #temp
    select a.personid,a.pid,@Level from tb a,#temp b where a.pid=b.personid and b.leve=@Level-1
    end select *from #temp