1

我真的很困惑RIGHT OUTER JOINsand LEFT OUTER JOINs。我真的很困惑如何正确使用它们。我在INNER JOIN. 我要问一些愚蠢的问题,但我问了它们是为了让我正确理解它们。

我怎么知道哪张桌子在右边和左边。是由哪个连接决定的吗?
我问所有这些问题是因为我正在使用 AdventureWorks 数据库并且我正在对下面的查询进行 LEFT JOIN

Select SalesLT.Customer.CompanyName, SalesLT.SalesOrderHeader.SubTotal, SalesLT.SalesOrderHeader.TaxAmt
FROM SalesLT.Customer
LEFT OUTER JOIN  SalesLT.SalesOrderHeader
ON  SalesLT.Customer.CustomerID  = SalesLT.SalesOrderHeader.CustomerID

这是我得到的结果

A Bike Store                NULL    NULL
Progressive Sports          NULL    NULL
Advanced Bike Components    NULL    NULL
Modular Cycle Systems       NULL    NULL
Metropolitan Sports Supply  NULL    NULL
Aerobic Exercise Company    NULL    NULL
Associated Bikes            NULL    NULL
Rural Cycle Emporium        NULL    NULL
Sharp Bikes                 NULL    NULL
 Bikes and Motorbikes       NULL    NULL

在同一个查询中,我用右外连接替换了左外连接连接,我得到了以下结果

Professional Sales and Service  39785.3304  3182.8264
Remarkable Bike Store           6634.2961   530.7437
Bulk Discount Store             88812.8625  7105.029
Coalition Bike Company          2415.6727   193.2538
Futuristic Bikes                246.7392    19.7391
Channel Outlet                  550.386     44.0309
Aerobic Exercise Company        2137.231    170.9785
Vigorous Sports Store           1059.31     84.7448

我真的很困惑。请向我解释这里发生了什么。可能是因为我没有正确完成加入。如果我错了,请纠正我。

谢谢你

4

2 回答 2

4

If a JOIN find matches for all rows then yes, it will look like an INNER JOIN. The OUTER part of joins is about what happens when a match cannot be found.

And the LEFT or RIGHT is saying which table's rows we always want to retain. So in a LEFT join, you'll always get all rows from the table to the left of the join, but for rows with no match on the right, we get NULLs. And for a RIGHT join, we always get all rows from the table to the right.

And as I say, if you're doing a LEFT join and every row in the left table has at least one matching row in the right table, the result will look the same as an INNER JOIN.

于 2014-11-13T14:08:12.840 回答
4

归还所有有储物柜的学生

Select * from Student s 
inner join locker l on s.StudentId = l.StudentId

归还所有学生,无论他们是否有储物柜。

Select * from Student s 
left join locker l on s.StudentId = l.StudentId

归还所有有储物柜的学生,以及是否有学生的所有储物柜

Select * from Student s 
right join locker l on s.StudentId = l.StudentId
于 2014-11-13T14:13:27.743 回答