简体   繁体   English

连接列别名的SQL语法

[英]SQL syntax to join on a column alias

I have a situation where I need to join tables on a common column name. 我有一种情况,我需要在公用列名上连接表。 I have some example SQL that shows what I am trying to do. 我有一些示例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

How can I rewrite the FAIL section above where I can join not on the column name from the table, but instead on an alias of that column name? 如何重写上面的FAIL部分,在其中我不能加入表中的列名,而不能加入该列名的别名?

You'll need to use a CTE or inline view (subquery). 您将需要使用CTE或内联视图(子查询)。 ON is evaluated well before the SELECT clause. SELECT子句之前先评估ON (Scroll to "Logical Processing Order of the SELECT statement.") (滚动到“ SELECT语句的逻辑处理顺序”。)

It's the same reason you can't use a column alias in the WHERE clause, or, well, anywhere else except the ORDER BY clause. 这是您不能在WHERE子句中或在ORDER BY子句以外的任何地方都不能使用列别名的原因。

This way: 这条路:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM