I am trying to apply a Left Join between two tables.
This is the First Table:
This is the Second Table:
Both are joined by WorkTypeId column.
Now the requirement is as such that if there is an entry in Table2 based on some userid then I should get all the worktypeid from Table 2 for that userid and the remaining worktypeid should come from Table1 with rest of the columns as 0 or 1.
Below is the query which i am trying to apply:
IF EXISTS (SELECT TOP 1 userid FROM Table2 WHERE UserId = @UserId)
BEGIN
Print 'inside If'
Select L.WorkType as WorkTypeName, UW.WorkTypeId,UW.IsChecked,UW.Active,UW.Priority
From Table1 L
Inner Join Table2 UW
On L.WorkTypeId = 1 --UW.WorkTypeId
Where UserId =99 ---@userId
And L.Active = 1
--Order By WorkTypeName ASC
UNION
SELECT L.WorkType as WorkTypeName,UW.WorkTypeId,0 as IsChecked,1 as Active,0 as Priority
From Table1 L
Left Join Table2 UW
On L.WorkTypeId =1 --UW.WorkTypeId
Where UserId =99 -- @userId
And L.Active = 1
AND UW.Priority IS NULL
END
But still I am seeing only one row which is the matching row and not other rows from left table along with hardcoded values.
EDIT 1 :
I have changed the query to below
Select L.WorkType as WorkTypeName, L.WorkTypeId,UW.IsChecked,UW.Active,UW.Priority
From Table1 L
Inner Join Table2 UW
On L.WorkTypeId = UW.WorkTypeId
Where UserId =99 ---@userId
And L.Active = 1
--Order By WorkTypeName ASC
UNION
SELECT L.WorkType as WorkTypeName,L.WorkTypeId,0 as IsChecked,1 as Active,0 as Priority
From Table1 L
Left Join Table2 UW
On UW.WorkTypeId = L.WorkTypeId
AND L.WorkTypeId Not In (Select WorkTypeId From UserWorkType Where UserId =99) --@UserId)
AND L.Active = 1
But still getting rows from both tables
I dont need the one marked with RED as this is already present in Table2.