SQL Server的Inner Join及Outer Join - sqlserver -

SQL Server的Inner Join及Outer Join

时间:2013-04-03 13:11:20   来源:   评论:加载中...   点击:加载中...
当然 Join 如何将不同的数据库的资料结合, 还要看你如何使用它, 一...

接下来删除 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 这项产品竟然找不到供货商的资料!



相关热词搜索:

 
上一篇:Sql语句密码验证的安全漏洞
下一篇:恢复系统数据库
收藏 将此文推荐给朋友
分享到: