简体   繁体   English

如何在 sql 连接中使用别名

[英]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:在我得到一个 sql 加入之后:

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:但是我不想使用变量“a,exit_date”我想根据我创建的变量(final_exit_date)替换它:喜欢它:

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.当您在SELECT列表中创建带有别名的表达式时,唯一允许您使用别名的地方是在ORDER BY子句中。 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.这让 SQL 中的许多人感到沮丧,因为别名通常在WHERE子句或其他地方有用,但这是不可能的。

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.另一种选择是使用公用表表达式 (CTE) 或子查询,以便别名可用。 Using a CTE, it would look something like this:使用 CTE,它看起来像这样:

;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.上面的查询可能存在一些问题,因为您没有包括表名或列(或者它们之间的关系),但是您应该能够通过采用这两种方法中的一种来创建可行的解决方案。

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

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