日期:2014-05-17  浏览次数:20447 次

一条sql????
想要的结果:

测试数据:


------解决方案--------------------

select a.name as '班长',b.name as '组长',c.name as '组员'
from (select * from tb where r_id=0)a
left join (select a.* from tb a inner join tb b on a.r_id=b.id where b.r_id=0)b on a.id=b.r_id
left join (
select a.*,b.r_id as new_id from tb a 
inner join (select a.* from tb a inner join tb b on a.r_id=b.id where b.r_id=0)b on a.r_id=b.id 
)c on a.id=c.new_id

------解决方案--------------------

create table pm
(id int,name varchar(10),r_id int,role varchar(10))

insert into pm
 select 1,'A',0,'班长' union all
 select 2,'B',1,'组长' union all
 select 3,'C',1,'组长' union all
 select 4,'D',2,'组员' union all
 select 5,'E',0,'班长' union all
 select 6,'F',5,'组长' union all
 select 7,'G',6,'组员' union all
 select 8,'H',6,'组员' union all
 select 9,'I',0,'班长'


select a.name '班长',b.name '组长',c.name '组员'
from (select * from pm where role='班长') a
left join (select * from pm where role='组长') b on a.id=b.r_id
left join (select * from pm where role='组员') c on b.id=c.r_id

/*
班长         组长         组员
---------- ---------- ----------
A          B          D
A          C          NULL
E          F          G
E          F          H
I          NULL       NULL

(5 row(s) affected)
*/

------解决方案--------------------
两表左联...
------解决方案--------------------