id parentid
1  root
2  root
3  2
4  1
5  1
6  1
7  2
8  root
9  root不要用存储过程,怎么用1个sql语句形成这样的结果,因为我要在mysql里用的,mysql的存储过程难用。1
   4
   5
   6 
2
   3
   7
8
9

解决方案 »

  1.   

    我现在仅仅需要2层的就够了。当然,如果能提供支持N层的单纯sql语句更好了。
      

  2.   

    http://topic.csdn.net/u/20090609/15/4a0d5206-fdc5-4d60-beb6-a1d66cd92806.html?56339
      

  3.   

    create table tb(id int,parentid int)
    insert into tb select 1,0 
    insert into tb select 2,0 
    insert into tb select 3,2 
    insert into tb select 4,1 
    insert into tb select 5,1 
    insert into tb select 6,1 
    insert into tb select 7,2 
    insert into tb select 8,0 
    insert into tb select 9,0 
    go
    select (case when parentid>0 then '  ' else '' end)+ltrim(id) from(
    select id,parentid,right('000'+ltrim(id),4) as pid from tb where parentid=0
    union all
    select id,parentid,right('000'+ltrim(parentid),4)+right('000'+ltrim(id),4)as pid from tb where parentid<>0
    )t order by pid
    go
    drop table tb
    /*
    1
      4
      5
      6
    2
      3
      7
    8
    9
    */
      

  4.   

    多谢7楼,我傍晚也想到了一样的方法。我要表达父项目和子项目的层次关系用子项目的父项目ID,跟父项目的项目ID,union之后,排序出来的,自然是父项目和子项目挨着的。 " select id id2,code code2,level level2,logindate logindate2\n"+
    " from sms_conf.project_list list1 \n"+
    " where 1=1 \n"+
    " and level=1 \n"+
    " union all \n"+
    " select id id2,parent code2 ,level level2 ,logindate logindate2 \n"+
    " from sms_conf.project_list list1 \n"+
    " where 1=1 \n"+
    " and level=2 \n"+
    " order by code2,level2,logindate2 "+
      

  5.   

    create table 表(id int,parentid int)
    insert into 表 select 1,0 
    insert into 表 select 2,0 
    insert into 表 select 3,2 
    insert into 表 select 4,1 
    insert into 表 select 5,1 
    insert into 表 select 6,1 
    insert into 表 select 7,2 
    insert into 表 select 8,0 
    insert into 表 select 9,0 
    select b.id 列,a.id into # from 表 a  join 表 b on a.parentid=b.id 
    order by 列,a.id
    select 列= case when exists (select 1 from # where Id<a.id and a.列=列) then '' else a.列 end,a.id  from # a
    drop table #    
         (5 行受影响)
    列           id
    ----------- -----------
    1           4
    0           5
    0           6
    2           3
    0           7(5 行受影响)