我地经常见到sql语句中 left outer join...    right outer join...  其实对于新手来讲见到呢d字眼系最头痛的。

首先现做个说明


左外连接就是左连接
右外连接就是右连接


简称而已


而左内 右内连接是不存在的



下面做个详细讲解。



首先建两个表作讲解用


员工表: employee_1 


左连接 like索引生效吗 sql中左连接怎么写_左外连接



同埋 部门表: dep_1


左连接 like索引生效吗 sql中左连接怎么写_左外连接_02



可以见到 Nedved这个人没分配部门,  而部门Network 没人。



内连接:


我地来睇下最常见的连接语句


select a.name, b.dep_name
from employee_1 a, dep_1 b
where a.dep = b.dep_id

可以见到只有4行, 其中没有分配的员工Nedved,和没人的部门Network都被排除了。

左连接 like索引生效吗 sql中左连接怎么写_左外连接_03



这种只筛选两张表中存在对应目标的数据  的连接就叫内连接。


其实内连接的标准写法是:


select a.name, b.dep_name
from employee_1 a
inner join dep_1 b on (a.dep = b.dep_id)

不过个人强烈建议第一种写法, 因为可读性大大比标准写法好太多,特别是连接超过3张表的时候。



左外连接:(又简称左连接)

表连接中,以左边的表为基准, 列出右表的对应数据。 也就是说即使左边的Nedved没有分配部门, 一样把他select出来,

只不过对应的部门名字为Null值。

左外连接写法:   注意 left join 实际上就是 left outer join 的简写,  右外连接同理。

select a.name, b.dep_name 
from employee_1 a 
left join dep_1 b on (a.dep = b.dep_id)


左连接 like索引生效吗 sql中左连接怎么写_数据库_04



分析下就知道, 内连接的结果实际上就是把左外连接的结果删掉 右表值为NULL得出的

也就是说:

左外连接相当于内连接再加上 左边那些在右表中找不到对应目标的数据的连接

等效于:


select a.name, b.dep_name
from employee_1 a,dep_1 b
where a.dep = b.dep_id
union
select a.name, Null
from employee_1 a
where not exists(select 1 from dep_1 b
                   where b.dep_id = a.dep)


在sybase中,左连接还可以这样写,注意与内连接差别很小哦

select a.name, b.dep_name
from employee_1 a, dep_1 b
where a.dep *=


在oracle中  左连接还可以这样写


select a.name, b.dep_name
from employee_1 a, dep_1 b
where a.dep(+) =


右外连接:(简称右连接)

刚好跟左外连接是相反的

表连接中,以右边的表为基准, 列出左表的对应数据。 也就是说即使右边的network部门没人, 一样把它select出来,

只不过对应的人名为Null值。


右外连接写法:


select a.name, b.dep_name
from employee_1 a
right join dep_1 b on (a.dep = b.dep_id)


左连接 like索引生效吗 sql中左连接怎么写_数据库_05



实际上 a left join b 等价于 b right join a。  这个唔难理解


同上,

右外连接相当于内连接再加上 右边那些在左表中找不到对应目标的数据的连接

等效于:


select a.name, b.dep_name
from employee_1 a,dep_1 b
where a.dep = b.dep_id
union
select null, b.dep_name
from dep_1 b
where not exists(select 1 from employee_1 a
                         where b.dep_id = a.dep)


在sybase中,右连接还可以这样写,

select a.name, b.dep_name
from employee_1 a, dep_1 b
where a.dep =*


在oracle中  右连接还可以这样写


select a.name, b.dep_name
from employee_1 a, dep_1 b
where a.dep = b.dep_id(+)


全外连接:(简称全连接)

跟左连接和右连接的集合(注意集合是没有重复数据的)

也就是说 把Nedved 和 部门Network都列出来了, 相应的值留空


全外连接写法:


select a.name, b.dep_name
from employee_1 a
full join dep_1 b on (a.dep = b.dep_id)


左连接 like索引生效吗 sql中左连接怎么写_左连接 like索引生效吗_06



注意oralce 下面写法是 错的, 全外连接没有其他写法(sybase  同理)

select a.name, b.dep_name 
from employee_1 a, dep_1 b
where a.dep  b.dep_id


全外连接实际上是

左外连接

union

右外连接


注意union 是回去掉重复数据的哦。



最后讲一句, 实际工作中,能用内连接就用内连接....