[英]How to use an alias in a sql join
我喜欢用案例创建一个变量:
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,
在我得到一个 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
当我这样做时,它会起作用。 但是我不想使用变量“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
预先感谢您阅读我!
当您在SELECT
列表中创建带有别名的表达式时,唯一允许您使用别名的地方是在ORDER BY
子句中。 这让 SQL 中的许多人感到沮丧,因为别名通常在WHERE
子句或其他地方有用,但这是不可能的。
解决方案是您必须复制表达式而不是使用别名。
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
另一种选择是使用公用表表达式 (CTE) 或子查询,以便别名可用。 使用 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
上面的查询可能存在一些问题,因为您没有包括表名或列(或者它们之间的关系),但是您应该能够通过采用这两种方法中的一种来创建可行的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.