如何从一个数据无序的树型表,得到一个数据工整排列的表?
原表
id upid name
1  0     aaa
2  0     bbb
3  2     cccc
4  1     ddddd
5  2     eeeee
6  1     fffff
7  4     gggg
8  4     hhhhh
........查询后得到的表
id upid name
1  0     aaa
4  1     ddddd
7  4     gggg
8  4     hhhhh
6  1     fffff
2  0     bbb
3  2     cccc
5  2     eeeee 
........

解决方案 »

  1.   

    他的关系如下图
    http://hotmy.com/cms/tmp/121.JPG
    是不是要用存储过程阿,存储过程怎么写呢?
    顶啊........分不够 再送...
      

  2.   

    class_id class_kiss class_base class_son class_tier class_name
    1        1      1         0      1         根分类1
    7    4          4       0      1           根分类4
    6        3      3       0      1           根分类3
    5    2        2       0      1           根分类2
    8           1:1        1         1      2         根1的子1
    9      1:1:1      1         1      3         根1的子1子1
    10          1:1:1:1    1         1        4         子子子
    11          1:1:1:1:1  1         1      5         子子子子
    12   1:1:1:1:1:1 1         1      6         子子子子子
    这种结构的表怎么理解,它和递归比较有什么优缺点?
      

  3.   

    class_id class_kiss class_base class_son class_tier class_name
    1          1        1         0      1         根分类1
    7          4           4       0      1          根分类4
    6          3        3       0      1   根分类3
    5          2          2       0      1   根分类2
    8          1:1         1         1      2         根1的子1
    9          1:1:1       1         1      3         根1的子1子1
    10         1:1:1:1     1         1      4         子子子
    11         1:1:1:1:1   1         1      5         子子子子
    12         1:1:1:1:1:1 1         1      6         子子子子子
      

  4.   

    create table A
    (
      id int,
      upid int,
      name varchar(10)
    )
    insert A
    select 1,  0,     'aaa' union
    select 2,  0,     'bbb' union
    select 3,  2,     'cccc' union
    select 4,  1,     'ddddd' union
    select 5,  2,     'eeeee' union
    select 6,  1,     'fffff' union
    select 7,  4,     'gggg' union
    select 8,  4,     'hhhhh'
    go--创建函数
    create function f_level(@id int,@level int)
    returns varchar(20)
    as
    begin
          declare @upid int
          set @id=isnull(@id,0)
          select  @upid=upid from A where id=@id
          if not exists(select 1 from A where id=@upid)
             return convert(varchar,@id)+'.'+convert(varchar,@level)      return dbo.f_level(@upid,@level+1)
    end
    go--查询
    select * from A 
    order by parsename(dbo.f_level(id,0),2)
             ,parsename(dbo.f_level(id,0),1)--删除测试环境
    drop function f_level
    drop table A--结果
    /*
    id          upid        name       
    ----------- ----------- ---------- 
    1           0           aaa
    4           1           ddddd
    6           1           fffff
    7           4           gggg
    8           4           hhhhh
    2           0           bbb
    3           2           cccc
    5           2           eeeee(8 row(s) affected)
    */