我需要一些关于左连接条件的帮助,我的查询如下
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)
这是输出
id name salary rating
1 Emp1 20000 B
2 Emp2 25000 A
3 Emp3 10000 C
4 Emp4 15000 D
5 Emp5 10000 C
从查询中可以看出,如果 oldsalaryid 为空,则使用 saleid 加入评级表。所以左连接完全基于列的值。这是正确的方法吗,通过查看数据,一切似乎都正确显示。我可以使用这个查询吗?