简体   繁体   中英

How to use an alias in a sql join

I create a variable with a case when like it:

case  when (a.exit_date='0001-01-01' and z.fermeture<>'0001-01-01') then z.fermeture
else a.exit_date
 end as final_exit_date,

And after I got a sql join like it:

select a.*,b.*

from   table1 as a
  left join table2 as b on (a.id=b.id and b.start <= a.exit_date and a.exit_date < b.end)

where a.id=28445

When I do it, it works. But me I don't want use the variable "a,exit_date" I want replace it per the variable that I created ( final_exit_date): like it:

select a.*,b.*

from   table1 as a
  left join table2 as b on (a.id = b.id and b.start <= final_exit_date and final_exit_date < b.end)

where a.id=28445

Thanks in advance for reading me !!

When you create an expression with an alias in a SELECT list, the only place you are allowed to use the alias is in the ORDER BY clause. This frustrates many people in SQL because it is often that the alias would be useful in a WHERE clause or elsewhere, but that is not possible.

The solution is that you have to duplicate the expression instead of using the alias.

SELECT a.*,b.*
FROM table1 AS a
-- you will need the z table as well
LEFT JOIN table2 AS b ON (a.id=b.id and b.start <= 
CASE WHEN (a.exit_date='0001-01-01' AND z.fermeture<>'0001-01-01') THEN z.fermeture ELSE a.exit_date END 
AND 
CASE WHEN (a.exit_date='0001-01-01' AND z.fermeture<>'0001-01-01') THEN z.fermeture ELSE a.exit_date END < b.end)
WHERE a.id=28445

Another option is to use a common table expression (CTE) or a subquery so that the alias is available. Using a CTE, it would look something like this:

;WITH records AS (
    SELECT a.*, CASE WHEN (a.exit_date='0001-01-01' AND z.fermeture<>'0001-01-01') THEN z.fermeture ELSE a.exit_date END AS final_exit_date
    FROM table1 AS a 
    LEFT OUTER JOIN otherTable AS z ON a.id = z.id -- whatever the condition is
) 
SELECT r.* b.* 
FROM records AS r 
LEFT JOIN table2 AS b ON r.id = b.id AND b.start<= r.final_exit_date AND r.final_exit_date < b.end

There are likely some issues with the query above since you didn't include the table names or the columns (or how they are even related), but you should be able to create a working solution by adapting one of these two approaches.

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