使用 SUBQUERY 和 JOIN 语句创建 SQL Server 2012 查询,需要第二双眼睛吗?

Creating a SQL Server 2012 Query with a SUBQUERY and a JOIN statement, need a second pair of eyes?

我正在尝试使用 AdventureWorks 2012 数据库编写 SQL Server 2012 查询代码作为学校作业的一部分,我创建了我的查询,但我不确定它是否足够干净且配置正确。

我应该同时使用子查询和连接语句。

"Return the customerid & territory id from the Customer table where the name on the SalesTerritory table is ‘Central’"

我不是在寻求任何方式作弊的帮助,我只是需要第二双眼睛,因为我很难弄清楚这一点,我几乎无法编程并且对它没有什么热爱。

到目前为止,这是我的查询:

SELECT Sales.Customer.CustomerID
       , Sales.Customer.TerritoryID,Sales.SalesTerritory.Name
FROM  Sales.Customer 
INNER JOIN Sales.SalesTerritory 
    ON Sales.Customer.TerritoryID = Sales.SalesTerritory.TerritoryID
WHERE (Sales.SalesTerritory.Name = N'central')
SELECT Sales.Customer.CustomerID, Sales.Customer.TerritoryID,    SalesTerritoryFiltered.Name
FROM   Sales.Customer 
INNER JOIN (SELECT *
            FROM Sales.SalesTerritory
            WHERE Sales.SalesTerritory.Name = N'central') SalesTerritoryFiltered
  ON Sales.Customer.TerritoryID  = SalesTerritoryFiltered.TerritoryID

这个有一个内部联接和子查询,其中包含您的过滤结果。未经测试但应该有效。

WHERE 替换为 AND 这会使过滤条件更有效,并在加入 table.so 时减少行提取次数,这也可能有助于提高性能!

SELECT Sales.Customer.CustomerID
      ,Sales.Customer.TerritoryID,Sales.SalesTerritory.Name
FROM  Sales.Customer 
INNER JOIN Sales.SalesTerritory 
ON Sales.Customer.TerritoryID = Sales.SalesTerritory.TerritoryID
AND Sales.SalesTerritory.Name = N'central'