建立如下表并插入数据:
create table s(
sid varchar2(10) primary key,
sname varchar2(50),
sage number(30));
insert into s values('111','小红',20);
insert into s values('222','小红',20);
insert into s values('333','小红',20);
insert into s values('555','小红',20);
create table c(
cid varchar2(10) primary key,
sid varchar2(10),
sscore number(3));
insert into c values('c1','111',20);
insert into c values('c2','222',20);
insert into c values('c3','333',20);
insert into c values('c4','444',20);
联接查询会有两组数据,一组数据对应一个表
外联接
1.左外联
左外联会查出左边表的全部数据,而右表只有和左边表关联的字段相等时( a.sid=b.sid),对应的记录才会显示,否则为空。
有两种写法:
①select * from s a left join c b on a.sid=b.sid; 左边的表中的记录全部显示
②select * from s a,c b where a.sid=b.sid(+); “+”号的另一边的表中的记录全部显示
查询结果:
2.右外联
右外联刚好和左外联相反,右外联会查出右边表的全部数据,而左表只有和右边表关联的字段相等时( a.sid=b.sid),对应的记录才会显示,否则为空。
有两种写法:
①select * from s a right join c b on a.sid=b.sid;
②select * from s a,c b where a.sid(+)=b.sid;
查询结果:
3.全外联
全外联两个表的所有记录(去除重复)都显示
SQL语句:
select * from s a full join c b on a.sid=b.sid;
查询结果:
内联接
内联接两张表都只显示满足条件(a.sid=b.sid)的记录
SQL语句:
select * from s a inner join c b on a.sid=b.sid;
查询结果: