Oracle语法温故(左外连接、右外连接、全外连接、内连接、自连接、联合查询 之间的区别)

来源:互联网 发布:找车用什么软件 编辑:程序博客网 时间:2024/06/03 23:47

 

不管是面试还是实际开发,SQL的关联查询总是用到最多的,这六种关联查询你是否明白他们的区别呢?

下面我做一个小小的例子,一看便知:

 

创建两张表,table1和table2

drop table table1;drop table table2;create table table1(id int,user_name varchar(50));create table table2(id int,user_name varchar(50));


向table1和table2中插入测试数据(加以区分,我将name字段中添加的数据指定了规则:表明_名称)

insert into table1 values( 1,'table1.outman1');insert into table1 values( 2,'table1.outman2');insert into table1 values( 3,'table1.outman3');insert into table1 values( 4,'table1.outman4');insert into table2 values( 1,'table2.outman1');insert into table2 values( 2,'table2.outman2');insert into table2 values( 3,'table2.outman3');insert into table2 values( 5,'table2.outman4');

 
左外连接查询:

-- 第一种方式select * from table1 left join table2 on table1.id = table2.id;-- 第二种方式select * from table1,table2 where table1.id = table2.id(+);

查询结果如下:

 

右外连接查询:

-- 第一种方式select * from table1 right join table2 on table1.id = table2.id;-- 第二种方式select * from table1,table2 where table1.id(+) = table2.id;

查询结果如下:

 

内连接查询:

select * from table1 inner join table2 on table1.id = table2.id;

查询结果如下:

 

全外连接查询:

select * from table1 full join table2 on table1.id = table2.id;

查询结果如下:


 

自连查询:

select * from table1, table1 table1_ where table1.id = table1_.id;

查询结果如下:

 

联合查询(不允许重复):

select id from table1union select id from table2;

查询结果如下:

 

联合查询(允许重复):

select id from table1union allselect id from table2;

查询结果如下:


关于联合查询:http://www.w3school.com.cn/sql/sql_union.asp

===============================  exists 替换 not in  ==================================

 

PS:这里介绍用exists 替换not in是出于对sql执行效率的考究,请看这里:

http://blog.csdn.net/zhuangzhineng/article/details/4463396

 

not in 查询如下:(table1显示的内容范围以ID作为条件,并排除table2相同于table1中的ID)

select * from table1 where table1.id not in       (select table2.id from table2 where table2.id = table1.id);

查询结果如下:

 

exists查询如下:(隐式比对,没有固定的字段作为条件,排除table2相同于table1中的ID,查询结果没任何区别)

select * from table1 where not exists(       select 1 from table2 where table2.id=table1.id);

查询结果如下:



 

 


 

原创粉丝点击