注册 登录
编程论坛 SQL Server论坛

请问自连接是怎么连接

yn136071 发布于 2008-10-29 20:35, 1287 次点击
我查了好多资料  还是每弄明白。
他是以什么样的方式连接呢?
2 回复
#2
卜酷塔2008-10-29 22:02
楼主看看下面的例子不知道会不会明白一点呢?
问题:emp表如下
id  name bossid
1  张三 0
2  杨杨 0
3  孙中 0
4  王一 1
5  李三 2

说明:bossid为0说明为顶头上司

我想要的结果是(我想建立视图):
id name bossid bossname
1 张三  0      
2 杨杨  0
3 孙中  0
4 五一  1      张三
5 李三  2      杨杨


If object_id('emp') is not null
    Drop table emp
Go
Create table emp(id int,name varchar(12),bossid int)
Go
Insert into emp
select 1,'张三',0 union all
select 2,'杨杨',0 union all
select 3,'孙中',0 union all
select 4,'王一',1 union all
select 5,'李三',2
Go
--Start
select a.id,a.name,a.bossid ,isnull(b.name,'') as bossname
from emp a left join emp b on a.bossid = b.id
#3
yn1360712008-10-29 23:05
呵呵,谢谢你。
明白了一些了。
1