如何在SQL JOIN关联条件中使用CASE WHEN定义的别名final_exit_date
问题解决方法
核心原因
SQL的执行顺序是FROM/JOIN → WHERE → SELECT,你在SELECT子句中定义的字段别名final_exit_date,在执行JOIN关联条件的阶段还没有被解析生成,因此直接在ON条件里引用别名会报错。
可行实现方案
方案1:直接把CASE WHEN表达式写到JOIN条件中(最简单高效)
直接把计算final_exit_date的逻辑内联到ON条件里即可,注意如果你的逻辑中用到了z.fermeture,需要先完成z表和a表的关联:
select a.*,b.* from table1 as a -- 如果用到z表需要先在这里关联z表,示例:left join table_z as z on a.关联字段 = z.关联字段 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
方案2:用子查询提前计算好别名字段
先通过子查询把final_exit_date计算完成,外层再关联b表,此时别名已经生效可以直接引用:
select t.*, b.* from ( 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 -- 同样需要在这里关联用到的z表 where a.id=28445 ) as t left join table2 as b on ( t.id = b.id and b.start <= t.final_exit_date and t.final_exit_date < b.end )
方案3:用CTE(公共表表达式)实现,可读性更高
逻辑和子查询一致,更适合多段复杂查询的场景:
with t 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 -- 关联z表的逻辑写在这里 where a.id=28445 ) select t.*, b.* from t left join table2 as b on ( t.id = b.id and b.start <= t.final_exit_date and t.final_exit_date < b.end )
内容的提问来源于stack exchange,提问作者fred
相关产品推荐
相关产品推荐

