要在列别名上连接的SQL语法

时间:2015-04-27 19:49:09

标签: sql sql-server

我遇到需要在公共列名上连接表的情况。我有一些示例SQL,显示了我想要做的事情。

declare @t table (assetid int)
declare @x table (id int)

insert into @t(assetid) values (1)
insert into @t(assetid) values (2)
insert into @t(assetid) values (3)

insert into @x(id) values (1)
insert into @x(id) values (2)
insert into @x(id) values (3)

-- SUCCESS
select assetid as assetid
from @t t 
inner join @x x on x.id = t.assetid

-- FAIL
select assetid as EntityId
from @t t 
inner join @x x on x.id = t.EntityId  <-- syntax error

如何重写上面的FAIL部分,我可以不加入表中的列名,而是加入该列名的别名?

2 个答案:

答案 0 :(得分:2)

您需要使用CTE或内联视图(子查询)。 ON is evaluated well before the SELECT clause.(滚动到“SELECT语句的逻辑处理顺序”。)

同样的原因是你不能在WHERE子句中使用列别名,或者除了ORDER BY子句之外的任何其他地方。

答案 1 :(得分:1)

这样:

select EntityId
    from (select assetid as EntityId from @t) t 
    inner join @x x on x.id = t.EntityId  
相关问题