Question

I have a situation where I need to join a table only on a particular condition.
Lets take the underwritten scenario

create table [premiumuser] (user_id int, name nvarchar(50));
create table [liteuser] (user_id int, name nvarchar(50));
create table [feature] (id nvarchar(50), user_id int, userkey int);

insert into [premiumuser] select 1, 'stephen';
insert into [premiumuser] select 2, 'roger';

insert into [liteuser] select 1, 'apollo';
insert into [liteuser] select 2, 'venus';

insert into feature select 'Upload content', 1, 1;
insert into feature select 'Create account', 1, 0;
insert into feature select 'View content', 2, 0;

Now I want to join only 1 table at a time from premiumUser or Lite user.

i.e.

select F.*, U.Name from feature 
Inner Join 
if condition 1 
 then 
  LiteUser U on U.User_Id = F.User_ID
 else
  PremiumUser U on U.User_Id = F.User_ID
end

Is there anyway to achieve this???

I know something like this can be done

   select 
      f.id,
      case when userkey=0 then l.name else p.name end as username
    from [feature] f
    left join [liteuser] l on l.user_id = f.user_id
    left join [premium user] p on p.user_id = f.user_id

but since I have huge tables I don't want to join both the tables. I want to be selective in joining the tables

Was it helpful?

Solution

No, you can't selective join in standard TSQL (definitely true for MS SQL and I'm pretty sure it's true for Oracle and MySQL).

You can however put the condition in the join. This will allow SQL to very quickly ignore the join because it will evaluate the conditions in order:

select 
  f.id,
  case when userkey=0 then l.name else p.name end as username
from [feature] f
left join [liteuser] l 
       on condition1 = 1 
      AND l.user_id = f.user_id
left join [premium user] p 
       on condition1 = 2
      and p.user_id = f.user_id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top