随笔 - 6  文章 - 0  trackbacks - 0

当需要从不止一个表中查询所需要的数据时,就要用到join。

最常用的join方式是inner join,其语法规则如下:
     select 字段名 from 主要资料表 inner join 次要资料表 on <join规则>
以northwind数据库为例,在QA中输入如下脚本:
     select ProductId, ProductName, Suppliers.CompanyName from Products
              inner join Suppliers on Products.SupplierId = 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 这项产品竟然找不到供货商的资料! 

posted on 2006-04-27 09:59 比尔德 阅读(635) 评论(0)  编辑  收藏 所属分类: 数据库开发