sql 外连接的写法。
首先現(xiàn)做個說明
左外連接就是左連接
右外連接就是右連接
簡稱而已
而左內(nèi) 右內(nèi)連接是不存在的
下面做個詳細(xì)講解。
首先建兩個表作講解用
員工表: employee_1?
同埋 部門表: dep_1
可以見到 Nedved這個人沒分配部門,? 而部門Network 沒人。
內(nèi)連接:
我地來睇下最常見的連接語句
select a.name, b.dep_name
from employee_1 a, dep_1 b
where a.dep = b.dep_id
這種只篩選兩張表中存在對應(yīng)目標(biāo)的數(shù)據(jù)? 的連接就叫內(nèi)連接。
其實內(nèi)連接的標(biāo)準(zhǔn)寫法是:
select a.name, b.dep_name
from employee_1 a
inner join dep_1 b on (a.dep = b.dep_id)
左外連接:(又簡稱左連接)
表連接中,以左邊的表為基準(zhǔn), 列出右表的對應(yīng)數(shù)據(jù)。 也就是說即使左邊的Nedved沒有分配部門, 一樣把他select出來,
只不過對應(yīng)的部門名字為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)
分析下就知道, 內(nèi)連接的結(jié)果實際上就是把左外連接的結(jié)果刪掉 右表值為NULL得出的
也就是說:
左外連接相當(dāng)于內(nèi)連接再加上 左邊那些在右表中找不到對應(yīng)目標(biāo)的數(shù)據(jù)的連接
等效于:
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中,左連接還可以這樣寫,注意與內(nèi)連接差別很小哦
select a.name, b.dep_name
from employee_1 a, dep_1 b
where a.dep *= b.dep_id
在oracle中? 左連接還可以這樣寫
select a.name, b.dep_name
from employee_1 a, dep_1 b
where a.dep(+) = b.dep_id
右外連接:(簡稱右連接)
剛好跟左外連接是相反的
表連接中,以右邊的表為基準(zhǔn), 列出左表的對應(yīng)數(shù)據(jù)。 也就是說即使右邊的network部門沒人, 一樣把它select出來,
只不過對應(yīng)的人名為Null值。
右外連接寫法:
select a.name, b.dep_name
from employee_1 a
right join dep_1 b on (a.dep = b.dep_id)
實際上 a left join b 等價于 b right join a。? 這個唔難理解
同上,
右外連接相當(dāng)于內(nèi)連接再加上 右邊那些在左表中找不到對應(yīng)目標(biāo)的數(shù)據(jù)的連接
等效于:
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 =* b.dep_id
在oracle中? 右連接還可以這樣寫
select a.name, b.dep_name
from employee_1 a, dep_1 b
where a.dep = b.dep_id(+)
全外連接:(簡稱全連接)
跟左連接和右連接的集合(注意集合是沒有重復(fù)數(shù)據(jù)的)
也就是說 把Nedved 和 部門Network都列出來了, 相應(yīng)的值留空
全外連接寫法:
select a.name, b.dep_name
from employee_1 a
full join dep_1 b on (a.dep = b.dep_id)
注意oralce 下面寫法是錯的, 全外連接沒有其他寫法(sybase? 同理)
select a.name, b.dep_name
from employee_1 a, dep_1 b
where a.dep(+) = b.dep_id(+)
全外連接實際上是
左外連接
union
右外連接
注意union 是回去掉重復(fù)數(shù)據(jù)的哦。
最后講一句, 實際工作中,能用內(nèi)連接就用內(nèi)連接....
總結(jié)
以上是生活随笔為你收集整理的sql 外连接的写法。的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]解决linux下sqldevelo
- 下一篇: 详解在group by分组查询中wher