不管是面试还是实际开发,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 table1
union
select id from table2;
查询结果如下:
联合查询(允许重复):
select id from table1
union all
select id from table2;
查询结果如下:
关于联合查询:http://www.w3school.com.cn/sql/sql_union.asp
=============================== exists 替换 not in ==================================
PS:这里介绍用exists 替换not in是出于对sql执行效率的考究,请看这里:
http://blog.youkuaiyun.com/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
);
查询结果如下: