现在的位置: 首页 > 综合 > 正文

database里面inner join和outer join有什么区别

2013年11月06日 ⁄ 综合 ⁄ 共 2292字 ⁄ 字号 评论关闭
出自:http://zhidao.baidu.com/question/23022899.html
介绍 Inner Join 及 Outer Join 以及其应用
Inner Join
Inner Join 应该是最常用的 Join 方式, 它只会传回符合 Join 规则的纪录, 还是先来看看语法
Select <要选择的字段> From <主要资料表>
<Join 方式> <次要资料表> [On <Join 规则>]
现在我们利用 MS SQL 内建的北风数据库来实际练习一下! 想多了解 MS SQL 的内建数据库, 你可以看看 SQL Server 的内建数据库 这篇文章
请打开 QA (Query Analyzer), 为了使用北风数据库, 请先执行 Use Northwind, 然后执行
Select ProductId, ProductName, SupplierId From Products
从 Products 产品资料表中取出三个字段, 分别是产品代码, 产品名称, 供货商代码, 但查询出来的结果保证让你的老板很不满意, 因为供货商代码对于人类实在是无虾米意义, 这个时候 Join 就可以帮上忙了, 藉由 Join Suppliers 这个资料表我们便可以查询到供货商名称
Select ProductId, ProductName, Suppliers.SupplierId
From Products
Inner Join Suppliers
Products.Suppliers = Suppliers.SupplierId
这款的查询结果是不是卡清楚呢! Inner Join 的主要精神就是 exclusive , 叫它做排他性吧! 就是讲 Join 规则不相符的资料就会被排除掉, 譬如讲在 Product 中有一项产品的供货商代码 (SupplierId), 没有出现在 Suppliers 资料表中, 那么这笔记录便会被排除掉
Outer Join
这款的 Join 方式是一般人比较少用到的, 甚至有些 SQL 的管理者也从未用过, 这真是一件悲哀的代志, 因为善用 Outer Join 是可以简化一些查询的工作的, 先来看看 Outer Join 的语法
Select <要查询的字段> From <Left 资料表>
<Left | Right> [Outer] Join <Right 资料表> On <Join 规则>
语法中的 Outer 是可以省略的, 例如你可以用 Left Join 或是 Right Join, 在本质上, Outer Join 是 inclusive, 叫它做包容性吧! 不同于 Inner Join 的排他性, 因此在 Left Outer Join 的查询结果会包含所有 Left 资料表的资料, 颠倒过来讲, Right Outer Join 的查询就会包含所有 Right 资料表的资料, 接下来我们还是来做些实际操作, 仍然是使用北风数据库, 但要先做一些小小的修改, 才能达到我们要的结果
首先要拿掉 Products 资料表的 Foreign Key, 否则没有法度在 Products 资料表新增一笔 SupplierId 没有对映到 Suppliers 资料表的纪录, 要知影一个资料表的 Constraint 你可以执行 SQL 内建的 sp_helpconstraint , 在 QA 执行
sp_helpconstraint Products
接下来删除 FK_Products_Suppliers 这个 Foreign Key
Alter Table Products
Drop Constraint FK_Products_Suppliers
再来新增一笔纪录于 Products 资料表, SupplierId 使用 50 是因为它并没有对映到 Suppliers 资料表中的记录
Insert Into Products (ProductName,SupplierId,CategoryId)
values ('Test Product','50','1')
现在我们再执行头前的查询, 只是将 Inner Join 改为 Left Outer Join
Select ProductId, ProductName, Suppliers.SupplierId
From Products
Left Outer Join Suppliers
Products.Suppliers = Suppliers.SupplierId
比较一下两种 Join 方式的查询结果, 你应该就会知影其中的差别!
再来看看 Right Outer Join, 请新增下底这笔记录
Insert Into Suppliers (CompanyName)
values ('LearnASP')
现在请使用 Right Out Join 来作查询, 比较看看查询的结果和 Inner Join 有什么不同!
寻找不相符纪录
这里我们来看看如何使用 Out Join 来找不相符纪录, 可能是有子纪录却没有父纪录或是颠倒过来
Select Suppliers.CompanyName From Products
Right Join Suppliers
On Products.SupplierId = Suppliers.SupplierId
Where Products.SupplierId is Null
执行结果你会找到一笔资料为 LearnASP, 该笔供货商资料存在, 但基本上已经没有产品是来自这个供货商, 想象一下如果不用 Outer Join 你要怎么以一个 SQL 指令完成同一查询结果! 知道 Outer Join 的好用了吧! 再执行
Select Products.ProductName
From Products
Left Join Suppliers
On Products.SupplierId = Suppliers.SupplierId
Where Suppliers.SupplierId is Null
这个查询结果你会发现 Test Product 这项产品竟然找不到供货商的资料!

抱歉!评论已关闭.