2

我正在加入 3 个表格,如下所示 -

select *
from Employee as e inner join [Grant] as g
on e.EmpID = g.EmpID -- "virtual table"  
inner join Location as l
on l.LocationID = e.LocationID

从 select 到 GrantID 的代码似乎是一个“虚拟表”。因此,它可以与另一个表(位置)连接以执行 3 表连接。我想给这个虚拟表一个别名。那可能吗 ?如果是,那我该怎么做?

注意 - 我使用 sql server 2008 express

4

3 回答 3

2

你不能这样做吗?

SELECT <columns>
FROM (SELECT <columns 2> FROM Employee as e INNER JOIN [Grant] as g on e.EmpID = g.EmpID) as t1
  INNER JOIN Location as l on t1.LocationID = l.LocationID

我不知道您要选择哪些列,因此是占位符。

于 2012-12-20T23:00:07.577 回答
2

CTE(通用表表达式)怎么样?像这样:

WITH    my_cte
          AS ( SELECT   e.EmpID as e_EmpID, g.* -- expand column list to only include required columns
               FROM     Employee AS e
                        INNER JOIN [Grant] AS g ON e.EmpID = g.EmpID -- "virtual table"  

             )
    SELECT  *
    FROM    my_cte
            INNER JOIN Location AS l ON l.LocationID = my_cte.LocationID;

Just know that if you refer to a CTE multiple times in the subsequent query the entire query is re-executed. If you need to refer to the CTE multiple times consider storing the results in a temp table first, then executing your query to join against the temp table.

于 2012-12-20T23:34:55.297 回答
1

也许这会做。

select *
from (select * from Employee as e 
inner join [Grant] as g on e.EmpID = g.EmpID) as vt
inner join Location as l on l.LocationID = vt.LocationID

只需确保列名不会在Employee和中重复Grant

于 2012-12-20T22:59:00.517 回答