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

关于Sql多表关联查询问题
------------------创建表及插入基础数据----------------------------  
--学生的信息
create table student(sid int,name varchar(20));
--读过的学校
create table shistory(sid int,school varchar(100));
--所有的爱好 
create table shobby(sid int,hobname varchar(200));
commit;
insert into student values(1,'laow'); 
insert into shistory values(1,'新泰某高中');
insert into shistory values(1,'山东某大学') ; 
insert into shobby values(1,'象棋');
insert into shobby values(1,'编程'); 
insert into shobby values(1,'游泳'); 

------------我的关联查询表---------------- 
select a.sid ,name,school, hobname 
from student a , shistory b , shobby c
where a.sid=b.sid and a.sid=c.sid 
order by name
结果:
SID NAME SCHOOL HOBNAME
1 laow 山东某大学 象棋
1 laow 新泰某高中 象棋
1 laow 新泰某高中 游泳
1 laow 新泰某高中 编程
1 laow 山东某大学 游泳
1 laow 山东某大学 编程

我想要的结果是:
SID NAME SCHOOL HOBNAME
1 laow 山东某大学 象棋
1 laow 新泰某高中 游泳
1 laow 空白空白空白 编程
如何实现? 坐等,感谢高手.
注*:School列和Hobname列的顺序无所谓
--删除表
drop table student;
drop table shistory;
drop table shobby;

------解决方案--------------------
SQL code

select a.sid ,name,school, hobname  
from student a , shistory b , shobby c
where a.sid=b.sid(+) 
and a.sid=c.sid(+)  
order by name

------解决方案--------------------
既然楼主是新人
就不要给人家灌输(+)的用法
楼主还是用left join吧,标准易读
select a.sid ,name,school, hobname
from student a 
left join shistory b on a.sid=b.sid
left join shobby c on a.sid=c.sid 
order by name
;
------解决方案--------------------
SQL code
select a.sid ,name,school, hobname  
from student a , shistory b , shobby c
where a.sid=b.sid(+) 
and a.sid=c.sid(+)  
order by name

------解决方案--------------------
SQL code

with b as
(
select a.*,row_number() over(partition by sid order by 1)  rn from shistory a
),
c as 
(select a.*,row_number() over(partition by sid order by 1)  rn 
from shobby a)
select a.sid ,name,school, hobname   
from  b  
full join  c on b.sid=c.sid  and b.rn=c.rn
right join student a on a.sid=nvl(b.sid,c.sid)
order by name
;