select col1
from table1
case when @col2 is null then left outer join else join end
table2 on (join condition)
以上是我的查询,我想根据1条件在左外连接或右外连接之间进行选择。
是否有更好的解决方案来实现上述问题
答案 0 :(得分:1)
我不确定这实际上是否可以按照描述的方式进行...我会写这样的东西;所以你根据你的附加条件短路一个JOIN。
select col1
from table1
left outer join table2
on (condition)
and @col2 is null
right outer join table2
on (condition)
and @col2 is not null
答案 1 :(得分:0)
select col1
from table1
left outer join
table2 on (join condition)
where @col2 is null or (@col2 is not null and table2.id is not null)
这将根据条件在left outer
或inner join
之间进行选择。
答案 2 :(得分:0)
使用此结构:
select *
from (
select
Key = 1,
-- remainder of left outer join
union all
select
Key=2,
-- remainder of right outer join
) T
where Key = case when (condition) then 1 else 2 end
答案 3 :(得分:0)
select col1
from table1 t1 full join table2 t2 on (join condition)
where case when @col2 is null then t2.col1 else t1.col1 end IS NOT NULL
您可以尝试使用此代码。