简体   繁体   中英

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.

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. I boiled down an example to show how I'd like to refer to the column name ( 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 :

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.

  2. Consider a sub query, so replace table2 with another select statement

    select * from A join (SELECT Col1 ColAlias from B) C on A.ColName = ColAlias

You can wrap the table in a CTE where you can assign new column names.

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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