当前位置: 移动技术网 > IT编程>数据库>Mysql > 解析:内联,左外联,右外联,全连接,交叉连接的区别

解析:内联,左外联,右外联,全连接,交叉连接的区别

2017年12月12日  | 移动技术网IT编程  | 我要评论

厦门小鱼社区,王开洲,菊爆盘

连接分为:内连接、外连接、交叉连接
一、内连接——最常用
定义:
仅将两个表中满足连接条件的行组合起来作为结果集。
在内连接中,只有在两个表中匹配的行才能在结果集中出现
关键词:inner join
格式:select 列名表 from 表名1 [inner] join 表名2 on或where 条件表达式
说明:
(1)列名表中的列名可以出自后面的两个表,但如果两个表中有同名列,应在列名前标明出处,格式为:表名.列名
(2)若连接的两个表名字太长,可以为它们起个别名。 格式为:表名 as 别名
(3)inner是默认方式,可以省略
eg:
select *
from   t_institution i
inner join t_teller t
on i.inst_no = t.inst_no
where i.inst_no = "5801"
其中inner可以省略。
等价于早期的连接语法
select *
from t_institution i, t_teller t
where i.inst_no = t.inst_no
and i.inst_no = "5801"

二、外连接
1、左(外)连接
定义:在内连接的基础上,还包含左表中所有不符合条件的数据行,并在其中的右表列填写null
关键字:left join
eg:
select *
from   t_institution i
left outer join t_teller t
on i.inst_no = t.inst_no
其中outer可以省略。
注意:
当在内连接查询中加入条件是,无论是将它加入到join子句,还是加入到where子句,其效果是完全一样的,但对于外连接情况就不同了。当把条件加入到 join子句时,sql server、informix会返回外连接表的全部行,然后使用指定的条件返回第二个表的行。如果将条件放到where子句 中,sql server将会首先进行连接操作,然后使用where子句对连接后的行进行筛选。下面的两个查询展示了条件放置位子对执行结果的影响:
条件在join子句
select *
from   t_institution i
left outer join t_teller t
on i.inst_no = t.inst_no
and i.inst_no = “5801”

结果是:
inst_no     inst_name             inst_no     teller_no   teller_name
5801        天河区                5801        0001        tom
5801        天河区                5801        0002        david
5802        越秀区
5803        白云区

条件在where子句
select *
from   t_institution i
left outer join t_teller t
on i.inst_no = t.inst_no
where i.inst_no = “5801”

结果是:
inst_no     inst_name             inst_no     teller_no   teller_name
5801           天河区                    5801          0001               tom
5801           天河区                    5801          0002              david

2、右(外)连接
定义:
在内连接的基础上,还包含右表中所有不符合条件的数据行,并在其中的左表列填写null
关键字:right join
3、完全连接
定义:
在内连接的基础上,还包含两个表中所有不符合条件的数据行,并在其中的左表、和右表列填写null
关键字:full join

三、交叉连接
定义:
将两个表的所有行进行组合,连接后的行数为两个表的乘积数。(笛卡尔积)
关键词:cross join
格式:from 表名1 cross join 表名2

四, 自身连接
自身连接是指同一个表自己与自己进行连接。这种一元连接通常用于从自反关系(也称作递归关系)中抽取数据。例如人力资源数据库中雇员与老板的关系。
下面例子是在机构表中查找本机构和上级机构的信息。
select s.inst_no superior_inst, s.inst_name sup_inst_name, i.inst_no, i.inst_name
from t_institution i
join t_institution s
on i.superior_inst = s.inst_no

结果是:
superior_inst sup_inst_name         inst_no     inst_name
800                             广州市                5801        天河区
800                             广州市                5802        越秀区
800                             广州市                5803        白云区

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网