I need some help with conditions on left join, my query is as follows
declare @emp table (id int, name varchar(100))
insert into @emp values (1,'Emp1')
insert into @emp values (2,'Emp2')
insert into @emp values (3,'Emp3')
insert into @emp values (4,'Emp4')
insert into @emp values (5,'Emp5')
--selecT * from @emp
declare @salary table(salaryid int, empid int, salary decimal(10,2))
insert into @Salary values (3,3,10000)
insert into @Salary values (4,4,15000)
insert into @Salary values (3,5,10000)
declare @oldsalary table(oldsalaryid int, empid int, oldsalary decimal(10,2))
insert into @oldsalary values (1,1,20000)
insert into @oldsalary values (2,2,25000)
--select * from @Salary
--select * from @oldsalary
declare @rating table (salaryid int, rating varchar(10))
insert into @rating values (4, 'D')
insert into @rating values (3, 'C')
insert into @rating values (1, 'B')
insert into @rating values (2, 'A')
--select * from @rating
select e.id, e.name, isnull(os.oldsalary, s.salary) salary, r.rating from @emp e
left join @salary s on e.id=s.empid
left join @oldsalary os on e.id=os.empid
left join @Rating r on r.salaryid = isnull(os.oldsalaryid, s.salaryid)
and this is the output
id name salary rating
1 Emp1 20000 B
2 Emp2 25000 A
3 Emp3 10000 C
4 Emp4 15000 D
5 Emp5 10000 C
As you can see from the query, if oldsalaryid is null then salaryid is used to join the rating table. So the left join is completely based on the value of the column. Is this the proper approach, by looking at the data everything seems to be showing correctly. Can I use this query?
What you are essentially telling SQL Server to do is to return all valuese from the @emp table. Then all items from the @salary table that has a match on the @emp table are being pulled in. After that, all values from the @oldsalary table that matches values on the @emp table are being pulled in. And the same with the @Rating table.
I prefer to to go with this approach of only using left joins instead of a combination of left and right joins. It gives the person reading the code a very clear picture of what the dominant tables in a comblex join are. As a result, you won’t need to read the FROM section of the statement backwards and forwards.