SQL的几种连接:内连接、外连接(左连接、右连接、全连接)

 表结构见前面博客

1.内连接

1.1.等值连接:在连接条件中使用等于号(=)运算符比较被连接列的列值,其查询结果中列出被连接表中的所有列,包括其中的重复列。

三种写法:

select * from t_fn_person a   , t_fn_dept b where a.dept_id=b.dept_id;
select * from t_fn_person a   join t_fn_dept b on a.dept_id=b.dept_id;
select * from t_fn_person a  inner join t_fn_dept b on a.dept_id=b.dept_id;

查询结果:

1.2.不等值连接:在连接条件使用除等于运算符以外的其它比较运算符比较被连接的列的列值。这些运算符包括>、>=、<=、<、!>、!<和<>。

1.3.自然连接:在连接条件中使用等于(=)运算符比较被连接列的列值,但它使用选择列表指出查询结果集合中所包括的列,并删除连接表中的重复列。

注:

内连接:内连接查询操作列出与连接条件匹配的数据行,它使用比较运算符比较被连接列的列值。

自然连接一定是等值连接,但等值连接不一定是自然连接。

等值连接要求相等的分量,不一定是公共属性;而自然连接要求相等的分量必须是公共属性。

等值连接不把重复的属性除去;而自然连接要把重复的属性除去。

2.外连接

2.1.左联接:是以左表为基准,将a.dept_id=b.dept_id的数据进行连接,然后将左表没有的对应项显示,右表的列为NULL

三种写法:

select * from  t_fn_person a   left join t_fn_dept b  on a.dept_id=b.dept_id;
select * from  t_fn_person a   left outer join t_fn_dept b  on a.dept_id=b.dept_id;
select * from  t_fn_person a   , t_fn_dept b  where a.dept_id=b.dept_id(+);

查询结果:

2.2.右连接:是以右表为基准,将a.dept_id=b.dept_id的数据进行连接,然以将右表没有的对应项显示,左表的列为NULL

三种写法:

select * from  t_fn_person a   right join t_fn_dept b  on a.dept_id=b.dept_id;
select * from  t_fn_person a   right outer join t_fn_dept b  on a.dept_id=b.dept_id;
select * from  t_fn_person a   , t_fn_dept b  where a.dept_id(+)=b.dept_id;

查询结果:

2.3.全连接:完整外部联接返回左表和右表中的所有行。当某行在另一个表中没有匹配行时,则另一个表的选择列表列包含空值。如果表之间有匹配行,则整个结果集行包含基表的数据值。

三种写法:

select * from  t_fn_person a   full join t_fn_dept b  on a.dept_id=b.dept_id;
select * from  t_fn_person a   full outer join t_fn_dept b  on a.dept_id=b.dept_id;

 查询结果:

参考: 参考(自然连接)

原文地址:https://www.cnblogs.com/hoaprox/p/10303936.html