表连接 - 性能

时间:2014-05-20 09:50:03

标签: sql-server performance self-join

我有一个名为Employee表的表,其中包含数据

Manager ManagerType Employee EmployeeType
A       Mgr1        Emp2     cat2
B       Mgr2        Emp3     Cat3
Emp3    Cat3        EmpX     Cat_X
Emp3    Cat3        EmpY     Cat_Y

现在我需要基于EmployeeType Column线性获取数据,我为其编写了一个带有case语句的case语句的select命令,我有大约12个级别的员工,我需要加入Employee表本身11次

道歉,这是代码

  select LEVEL0.Manager AS LEVEL0_Manager    
 ,LEVEL0.Employee AS LEVEL0_Employee, LEVEL0.EmployeeType AS LEVEL0_EmployeeType    
 ,LEVEL1.Employee AS LEVEL1_Employee, LEVEL1.EmployeeType AS LEVEL1_EmployeeType    
 ,LEVEL2.Employee AS LEVEL2_Employee, LEVEL2.EmployeeType AS LEVEL2_EmployeeType    
 ,LEVEL3.Employee AS LEVEL3_Employee, LEVEL3.EmployeeType AS LEVEL3_EmployeeType    
 ,LEVEL4.Employee AS LEVEL4_Employee, LEVEL4.EmployeeType AS LEVEL4_EmployeeType    
 ,LEVEL5.Employee AS LEVEL5_Employee, LEVEL5.EmployeeType AS LEVEL5_EmployeeType    
 ,LEVEL6.Employee AS LEVEL6_Employee, LEVEL6.EmployeeType AS LEVEL6_EmployeeType    
 ,LEVEL7.Employee AS LEVEL7_Employee, LEVEL7.EmployeeType AS LEVEL7_EmployeeType    
 ,LEVEL8.Employee AS LEVEL8_Employee, LEVEL8.EmployeeType AS LEVEL8_EmployeeType    
 ,LEVEL9.Employee AS LEVEL9_Employee, LEVEL9.EmployeeType AS LEVEL9_EmployeeType    
 ,LEVEL10.Employee AS LEVEL10_Employee, LEVEL10.EmployeeType AS LEVEL10_EmployeeType    
 ,LEVEL11.Employee AS LEVEL11_Employee, LEVEL11.EmployeeType AS LEVEL11_EmployeeType    
 INTO #Relation_Level_12    
 from Employee  LEVEL0    
 LEFT JOIN Employee  LEVEL1 ON LEVEL0.Employee = LEVEL1.Manager    
 LEFT JOIN Employee  LEVEL2 ON LEVEL1.Employee = LEVEL2.Manager    
 LEFT JOIN Employee  LEVEL3 ON LEVEL2.Employee = LEVEL3.Manager    
 LEFT JOIN Employee  LEVEL4 ON LEVEL3.Employee = LEVEL4.Manager    
 LEFT JOIN Employee  LEVEL5 ON LEVEL4.Employee = LEVEL5.Manager    
 LEFT JOIN Employee  LEVEL6 ON LEVEL5.Employee = LEVEL6.Manager    
 LEFT JOIN Employee  LEVEL7 ON LEVEL6.Employee = LEVEL7.Manager    
 LEFT JOIN Employee  LEVEL8 ON LEVEL7.Employee = LEVEL8.Manager    
 LEFT JOIN Employee  LEVEL9 ON LEVEL8.Employee = LEVEL9.Manager    
 LEFT JOIN Employee  LEVEL10 ON LEVEL9.Employee = LEVEL10.Manager    
 LEFT JOIN Employee  LEVEL11 ON LEVEL10.Employee = LEVEL11.Manager    
 where LEVEL0.ManagerType  = 'Mgr1' 

员工表获得了大约3000万条记录

问题是,如果自己加入Employee表11次,或者将一个连接级别逐级查询到临时表和下一级别,那么执行是否有效。我使用临时表连接与Employee表来形成另一个临时表。喜欢明智的11次达到相同的结果还是上面的查询更好?

1 个答案:

答案 0 :(得分:1)

使用递归公用表表达式来获取此数据。

有一个例子非常适合您在Technet上的情况:http://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx