当前位置: 代码迷 >> SQL >> sql之left join、right join、inner join full join,union,union all的差异
  详细解决方案

sql之left join、right join、inner join full join,union,union all的差异

热度:41   发布时间:2016-05-05 14:02:32.0
sql之left join、right join、inner join full join,union,union all的区别
left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录
right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录
inner join(等值连接) 只返回两个表中联结字段相等的行
full join 返回两张表中的行 left join+right join
UNION在进行表链接后会筛选掉重复的记录
UNION ALL操作只是简单的将两个结果合并后就返回

create table test(
sid number primary key not null,
sname varchar2(200),
scode varchar2(200)
);
commit;

create table test_bak(
sid number primary key not null,
sname varchar2(200),
scode varchar2(200)
);
commit;

BEGIN
  FOR I IN 1 .. 4 LOOP
    INSERT INTO test VALUES (I,'jason','1000'+i);
  END LOOP;
END;

BEGIN
  FOR I IN 3 .. 5 LOOP
    INSERT INTO test_bak VALUES (I,'jason','1000'+i);
  END LOOP;
END;

select * from test;
sid sname scode
1 1 jason 1001
2 2 jason 1002
3 3 jason 1003
4 4 jason 1004
select * from test_bak;
sid sname scode
1 3 jason 1003
2 4 jason 1004
3 5 jason 1005
select * from test union    select * from test_bak;--UNION在进行表链接后会筛选掉重复的记录
sid sname scode
1 1 jason 1001
2 2 jason 1002
3 3 jason 1003
4 4 jason 1004
5 5 jason 1005

select * from test union  all  select * from test_bak;--UNION ALL操作只是简单的将两个结果合并后就返回
sid sname scode
1 1 jason 1001
2 2 jason 1002
3 3 jason 1003
4 4 jason 1004
5 3 jason 1003
6 4 jason 1004
7 5 jason 1005

select test.*,test_bak.* from test  inner join test_bak on test.sid = test_bak.sid  ;--只返回两个表中联结字段相等的行
1 3 jason 1003 3 jason 1003
2 4 jason 1004 4 jason 1004

select test.*,test_bak.* from test left join test_bak on test.sid = test_bak.sid  ;--返回包括左表中的所有记录和右表中联结字段相等的记录
1 1 jason 1001 null null null
2 2 jason 1002 null null null
3 3 jason 1003 3 jason 1003
4 4 jason 1004 4 jason 1004

select test.*,test_bak.* from test right join test_bak on test.sid = test_bak.sid  ;--返回包括右表中的所有记录和左表中联结字段相等的记录

1 3 jason 1003 3 jason 1003
2 4 jason 1004 4 jason 1004
3 null null null 5 jason 1005

select test.*,test_bak.* from test full join test_bak on test.sid = test_bak.sid  ;--返回左右两表中的所有记录,相同的记录会同行显示

1 1 jason 1001 null null null
2 2 jason 1002 null null null
3 3 jason 1003 3 jason 1003
4 4 jason 1004 4 jason 1004
5 null null null 5 jason 1005
  相关解决方案