Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CASE Statements in LEFT OUTER JOIN in SQL

I've got a scenario where I want to switch on two different tables in an outer join. It goes something like this:-

         select mytable.id, 
                yourtable.id
           from mytable
left outer join (case
                    when mytable.id = 2 then table2 
                      yourtable on table1.id = table2.id
                    else
                      table3 yourtable on table1.id = table3.id
                 end)

...but it doesn't work. Any suggestions?

like image 633
s khan Avatar asked Mar 22 '10 05:03

s khan


People also ask

In which case would you use a left outer join?

Left and right outer joins are useful if you want to get all the values from one table but only the rows that match that table from the other table. So in a left outer join, all rows from the left table will be returned plus the rows that the right table had in common.

Can we use CASE statement in join condition in SQL Server?

There are plenty of ways to resolve for this: a subquery with a CASE statement in the join statement for the table you are joining in, a CASE statement in a temp table where all values are changed to match, or this handy little trick of using a CASE statement in the JOIN's ON clause.

Can case be used in join?

Yes, the CASE clause can be used inside the join conditions of the VQL query.

Which cases in outer join?

OUTER JOIN is utilized for returning data from all rows from both the joined tables that satisfy JOIN condition and return all data from the rows which does not satisfy the same JOIN condition. The OUTER JOIN should be used utilized within the JOIN condition only.


1 Answers

Use (Oracle 9i+):

   SELECT mt.id, 
          COALESCE(yt1.id, yt2.id)
     FROM MYTABLE mt
LEFT JOIN YOURTABLE yt1 ON yt1.id = mt.id
                       AND yt.id = 2
LEFT JOIN YOURTABLE yt2 ON yt2.id = mt.id
like image 127
OMG Ponies Avatar answered Sep 17 '22 00:09

OMG Ponies