最优?什么概念?
按你的提示写出来速度一定不是最优的。declare @Temp table (id int)insert @Temp
select id from tablename where name='AAA'  ---很想用pid=0,但你没有说明pid的概念。while exists (
select id from tablename a 
where exists (select 1 from @Temp where id=a.pid) 
and not exists (select 1 from @Temp where id=a.id) 
)
insert @Temp
select id from tablename a 
where exists (select 1 from @Temp where id=a.pid) 
and not exists (select 1 from @Temp where id=a.id) select * from tablename a 
where not exists (select 1 from @Temp where id=a.id) 

解决方案 »

  1.   

    这个一定不是比赛题,因为设计臃(不好意思,大不出那个字)余太大,而且没有说明PID和ID的关系,出这样题的老师该下岗!
      

  2.   

    楼主说明:PID为该节点的父节点,第一层的pid为0。本题要求用一条sql语句完成。
      

  3.   

    要讲究速度就不应该要求一条语句.select * from tablename a 
    where name<>'AAA' 
    and not exists (
      select 1 from tablename b 
      where exists     (
          select 1 from tablename c 
          where name='AAA' 
          and id=b.pid
          )
      and a.PATH like '%>'+cast (b.id as varchar(8))+'>%'
      )
      

  4.   

    痛恨"罪尤"SQLselect a.* from tuser a
    where a.name<>'AAA' AND not exists 
      (select ID from tuser 
       where [user]=a.[user] and name='AAA' and patindex('%>'+convert(varchar(5),ID)+'>%',a.path)>1)
      

  5.   

    select a.* from tuser a
    where a.name<>'AAA' AND not exists 
      (select ID from tuser 
       where name='AAA' and patindex('%>'+convert(varchar(5),ID) +'>%',a.path)>1)
     也可以的.