使用别名的子查询

许多其中的子查询和外部查询引用同一表的语句可称为自联接(将某个表与自身联接)。例如,可以使用子查询查找与 Terri Duffy 具有相同经理的雇员:

USE AdventureWorks;
GO
SELECT EmployeeID, ManagerID
FROM HumanResources.Employee
WHERE ManagerID IN
    (SELECT ManagerID
     FROM HumanResources.Employee
     WHERE EmployeeID = 12)

下面是结果集: 

EmployeeID  ManagerID
----------- -----------
6           109
12          109
21          109
42          109
140         109
148         109
273         109

(7 row(s) affected)

也可以使用自联接:

USE AdventureWorks;
GO
SELECT e1.EmployeeID, e1.ManagerID
FROM HumanResources.Employee AS e1
INNER JOIN HumanResources.Employee AS e2
ON e1.ManagerID = e2.ManagerID
AND e2.EmployeeID = 12

由于自联接的表会以两种不同的角色出现,因此必须有表别名。别名也可用于在内部查询和外部查询中引用同一表的嵌套查询。

USE AdventureWorks;
GO
SELECT e1.EmployeeID, e1.ManagerID
FROM HumanResources.Employee AS e1
WHERE e1.ManagerID IN
    (SELECT e2.ManagerID
     FROM HumanResources.Employee AS e2
     WHERE e2.EmployeeID = 12)

显式别名清楚地表明,在子查询中对 HumanResources.Employee 的引用并不等同于在外部查询中的该引用。

请参阅

概念

子查询类型

帮助和信息

获取 SQL Server 2005 帮助