Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server left join if condition met

Tags:

sql-server

I have a problem with my query. I have to do left outer join only if condition is true. If condition is false do another left outer join.

I tried with this but not successfully:

select 
    * 
from 
    works with(nolock) 
if work.type = 1 
begin
    left outer join 
        users with(nolock) on users.id = work.owner
else
    left outer join 
        groups with(nolock) on groups.id = work.owner
end

How can I solve this problem?

like image 931
frasca Avatar asked Jul 11 '26 08:07

frasca


1 Answers

you should try left join both of them, but inside of the select, take what you want depending on the use case.

SELECT
  *, 
  CASE work.type WHEN '1' THEN 'a.owner' ELSE 'b.owner' END AS owner
FROM
  blahblah
  left join users on blahblah.user_id = users.id as a,
  left join groups as blahblah.groups_id = groups.id as b
like image 74
Dylan Ang Avatar answered Jul 18 '26 22:07

Dylan Ang