不一般的sql语句

一个热爱bug的程序猿 2011-03-04 04:06:32
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语句改怎么写
...全文
84 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
晕!这么简单啊,sql没学好啊!以后得继续向大家请教了!谢谢各位的回答,由于分数有限,只能大致均分了啊
高山 2011-03-04
  • 打赏
  • 举报
回复

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 tab6

select a.tid,a.tname,b.tname
from tab6 a,tab6 b
where a.topid=b.tid

tid tname tname
----------- ---------- ----------
3 ccc aaa
4 ddd aaa
5 eee bbb
6 fff bbb

(4 row(s) affected)

快溜 2011-03-04
  • 打赏
  • 举报
回复
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
子陌红尘 2011-03-04
  • 打赏
  • 举报
回复
select b.id,b.name,a.name as topname from tname a,tname b where a.id=b.topid order by b.id

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧