帮想一个SQL:
表结构:
id    pid
1      0
2      1
3      2
4      2
现在已知3,4需要查出:2,1,0
也就是要查询3,4的父id---2
包括它父id 2的父id---1
和1的父id------0

解决方案 »

  1.   

    sql不知道怎么写,要是程序加sql的话,就需要递归了。
      

  2.   

    恩 是可以 艾  不到万不得已 
    我还是不太希望用程序递归的方法
    还是觉得一条SQL应该可以查出来的吧
      

  3.   

    父亲的父亲的父亲。 
    如果不使用递归想一次查询出来,
    我想每多一层就要加一个join语句了。
      

  4.   

    oracle 用start with是可以的
    select * from table start with pid=0 connect by prior id = pid
    sql2000怎么写啊?
      

  5.   

    sql2000呀,手头没有2000哦!
      

  6.   

    SQL 问题请先说明用的是什么数据库!
      

  7.   

    oracle:
    select pid from tree1 start with id=4 connect by prior pid = id;
    急求sql2000的
      

  8.   

    做个参考吧。create table child_parent
    ( [id] int primary key ,
      [pid] int 
    )
    go
    --灌入你的数据
    insert into child_parent values (1 ,0)
    insert into child_parent values (2 ,1)
    insert into child_parent values (3 ,2)
    insert into child_parent values (4 ,2)
    select * from child_parent--做一个临时表,用于存储闭包
    create table #child_ancester
    ( [id] int,
      [aid] int,
      primary key([id], [aid])
    )
    go--计算闭包
    insert into #child_ancester(id, aid) select * from child_parent
    while @@rowcount>0
    begin
    insert into #child_ancester(id, aid) 
      select c.[id], a.[aid] from child_parent as c, #child_ancester as a where c.[pid]=a.[id]
        and not exists (
          select * from #child_ancester aa where c.[id]=aa.[id] and a.[aid]=aa.[aid]
                        )
    end--用闭包表来查询祖先
    select distinct aid from #child_ancester
      where [id] in (3,4)--删除临时表
    drop table #child_ancester
      

  9.   

    T-SQL是Server端执行的程序代码,LZ所谓程序迭代指的是客户端程序实现吧。
    在大数据量的情况下,T-SQL性能应该更好。
    如果配合使用触发器,在更新child_parent的时候自动更新child_ancester,对于查询工作,就简化到只需要查询child_ancester表这样简单的程度了。Oracle不错,毕竟是数据库老大。
      

  10.   

    嘎嘎,这是层次查询。所有rdbms里面只有oracle有connect by的层次查询功能,其他的没一个有的。偶做过类似的,mysql 的。不过直接用sql写很困难,我曲线了一把,思路如下:给表格添加一列,名字就叫做levelRelation 层次关系,列出了每行数据所在层次的深度。
    id pid levelRelation
    1  0    0
    2  1    1
    3  2    1.1
    4  2    1.2 
    5  2    1.2.1
    6  2    1.2.2
    7  3    1.3
    8  3    1.4
    9  3    1.4.1
    10 3    1.4.2然后就好办了。如果你要查询主键是6的父亲和儿子,直接获取6的层次深度比如是6.1.2,那么它的父亲肯定是6.1,儿子就是6.1.2.*(如果有的话)。获取了儿子或父亲的层次深度,再反查它的id就容易的多了。你的sql就知道怎么写了吧。接下来你该问了,层次深度怎么计算?下文回见。