id name topid
1   aaa   0
2   bbb   0
3   ccc   1
4   ddd   1
5   eee   2
6   fff   2
这是数据表的格式,现在需要显示如下:
id   name topname
3    ccc   aaa
4    ddd   aaa
5    eee   bbb
6    fff   bbb
sql语句改怎么写

解决方案 »

  1.   

    select b.id,b.name,a.name as topname from tname a,tname b where a.id=b.topid order by b.id
      

  2.   

    select id,name,c.name as topname 
     from tb a left join tb b on a.topid=b.id
    where c.name is not null 
      

  3.   


    create table tab6
    (
    tid int,
    tname varchar(10),
    topid int
    )
    insert into tab6
    select 1,'aaa',0 union all
    select 2,'bbb',0 union all
    select 3,'ccc',1 union all
    select 4,'ddd',1 union all
    select 5,'eee',2 union all
    select 6,'fff',2 select * from tab6select a.tid,a.tname,b.tname
    from tab6 a,tab6 b
    where a.topid=b.tidtid         tname      tname      
    ----------- ---------- ---------- 
    3           ccc        aaa
    4           ddd        aaa
    5           eee        bbb
    6           fff        bbb(4 row(s) affected)
      

  4.   

    晕!这么简单啊,sql没学好啊!以后得继续向大家请教了!谢谢各位的回答,由于分数有限,只能大致均分了啊