简体   繁体   English

SQL Server / TSQL:在联接中别名表别名

[英]SQL Server/TSQL : Aliasing a column on table alias in join

For efficiency, I'm trying to find out if there is a syntax which allows me to alias a column on a table using that table alias entirely in the from section and join sections. 为了提高效率,我试图找出一种语法,该语法允许我在from部分和join部分中完全使用该表别名对表中的列进行别名。

I know I could alias the column in the SELECT, but if I were using select * (I know, not good practice) it would not be available. 我知道我可以为SELECT中的列加别名,但是如果我使用select *(我知道,不是一个好习惯),它将不可用。 I boiled down an example to show how I'd like to refer to the column name ( doubleAlias ): doubleAlias了一个示例来说明如何引用列名( doubleAlias ):

SELECT * 
FROM [table1] AS tl
   JOIN [table2] AS t2
   ON t1.[column1] = t2.[column1] AS doubleAlias
    WHERE doubleAlias = 'value';
--INSTEAD OF
  --WHERE t2.[column1] = 'value'; 

In SQL Server, you can use outer apply : 在SQL Server中,可以使用outer apply

SELECT t1.*, t2.*
FROM [table1] tl JOIN
     [table2] t2
     ON t1.[column1] = t2.[column1] OUTER APPLY
     (VALUES (t1.column1) ) v(doubleAlias)
WHERE doubleAlias = 'value';

There are at least two methods of double aliasing a column, just not with the syntax you chose. 至少有两种双列别名的方法,只是不使用您选择的语法。

  1. Consider replacing table2 with a view, you can alias the columns as much as you want within the view. 考虑用视图替换table2,您可以在视图中根据需要为列添加别名。

  2. Consider a sub query, so replace table2 with another select statement 考虑一个子查询,因此用另一个select语句替换table2

    select * from A join (SELECT Col1 ColAlias from B) C on A.ColName = ColAlias 在A.ColName = ColAlias上的A联接中选择*(从B选择SELECT Col1 ColAlias)C

You can wrap the table in a CTE where you can assign new column names. 您可以将表包装在CTE中,在其中可以分配新的列名。

WITH t2 AS (
    SELECT *, column1 AS doubleAlias
    FROM [table2] 
)
SELECT *
FROM [table1] AS tl
JOIN t2
   ON t1.[column1] = t2.[doubleAlias]
WHERE t2.doubleAlias = 'value';

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

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