我正在加入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
答案 0 :(得分: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
我不知道您要选择哪些列,因此占位符。
答案 1 :(得分: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;
只要知道如果在后续查询中多次引用CTE,就会重新执行整个查询。如果需要多次引用CTE,请考虑先将结果存储在临时表中,然后执行查询以加入临时表。
答案 2 :(得分: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
中重复出现。