我目前正在MS SQL Server 2012中进行复杂的T-SQL查询。我基本上检索了一个基本的项目列表,包含ProjectId以及StaffVersionId(工作人员可能会在整个项目中进行更改,虽然我希望情况不是这样:P)。
CREATE TABLE #BasicProjects
(
ProjectId INT
, StaffVersionId INT
)
接下来,我需要加入ProjectData Table以获取项目的标题,并加入Employee Table以获取Employee的FullName。
SELECT [P].ProjectId
, [PD].Label AS Title
, [E].Lastname + '' '' + Firstname AS Manager
, [E].Lastname + '' '' + Firstname AS Contact
FROM #BasicProjects [P]
INNER JOIN [MySchema].[ProjectData] [PD] ON [PD].ProjectDataId = [P].ProjectDataId
INNER JOIN [MySchema].[Staff] [Y] ON [Y].StaffVersionId = [P].StaffVersionId AND [Y].StaffTypeId = 3 // Manager
INNER JOIN [MySchema].[Staff] [X] ON [X].StaffVersionId = [P].StaffVersionId AND [X].StaffTypeId = 2 // Contact
INNER JOIN [dbo].[Employee] [E] ON [E].EmployeeId = [Y].EmployeeId
INNER JOIN [dbo].[Employee] [E] ON [E].EmployeeId = [X].EmployeeId
查询有点难,因为我有2种员工3 =经理,2 =联系。
当我运行查询时,我收到此错误:
在FROM子句中多次指定相关名称“E”。
你知道如何解决这个错误吗?或者也许有人建议如何改进这个查询?
非常感谢!
答案 0 :(得分:2)
每个联接需要不同的别名(就像您对Staff
所做的那样)
SELECT [P].ProjectId
, [PD].Label AS Title
, [YE].Lastname + ' ' + YE.Firstname AS Manager
, [XE].Lastname + ' ' + XE.Firstname AS Contact
FROM #BasicProjects [P]
INNER JOIN [MySchema].[ProjectData] [PD] ON [PD].ProjectDataId = [P].ProjectDataId
INNER JOIN [MySchema].[Staff] [Y] ON [Y].StaffVersionId = [P].StaffVersionId AND [Y].StaffTypeId = 3 // Manager
INNER JOIN [MySchema].[Staff] [X] ON [X].StaffVersionId = [P].StaffVersionId AND [X].StaffTypeId = 2 // Contact
INNER JOIN [dbo].[Employee] [YE] ON [YE].EmployeeId = [Y].EmployeeId
INNER JOIN [dbo].[Employee] [XE] ON [XE].EmployeeId = [X].EmployeeId