Do Left or Inner Join depends on parameter
I have to do 'left' or 'inner' join operation between tables depends on input parameter in my stored procedure. I know how to 开发者_如何转开发do it very simply:
if flag = 0
begin
select t1.*, t2.* from t1
inner join t2 on t2.id=t1.id
end
else
begin
select t1.*, t2.* from t1
left join t2 on t2.id=t1.id
end
Is there any more solution ? Thank you
you can do it using only left join by doing something like this
select t1.*, t2.* from t1
left outer join t2 on t2.id=t1.id
WHERE flag = 1 OR t2.id IS NOT NULL
You didn't mention the language, so maybe something like this:
select t1.*, t2.* from t1
left join t2 on t2.id=t1.id
if flag = 0
begin
where t2.id is not null
end
select t1.*, t2.*
from t1
inner join t2 on t2.id = t1.id
where flag = 0
UNION
select t1.*, t2.*
from t1
left outer join t2 on t2.id = t1.id
where coalesce(flag, 1) <> 0;
精彩评论