这是一个人为的例子,但考虑一个场景,员工有工作地点,员工也有经理,他们也有工作地点:
create table WorkingLocation (
ID int not null primary key identity(1,1),
Name varchar(50)
)
create table Employee (
ID int not null primary key identity(1,1),
Name varchar(50),
WorkingLocationID int null,
ManagerID int null,
constraint FK_Employee_WorkingLocation foreign key (WorkingLocationID) references WorkingLocation (ID),
constraint FK_Employee_Manager foreign key (ManagerID) references Employee (ID)
)
Run Code Online (Sandbox Code Playgroud)
现在考虑一个想要雇员的商业规则WorkingLocation,但是WorkingLocation如果他没有经理人的话,他会满足于他的经理人.此时您有两个选择:
1:有一个获取两者的查询,让业务规则决定使用哪个:
select
e.*,
emp_location.*,
mgr_location.*
from Employee e
left join WorkingLocation emp_location on e.WorkingLocationID = emp_location.ID
left join Employee mgr on e.ManagerID = mgr.ID
left join WorkingLocation mgr_location on mgr.WorkingLocationID = mgr_location.ID
where e.ID = @id
Run Code Online (Sandbox Code Playgroud)
2:如果员工没有WorkingLocation设置,则单独调用数据库以检索经理的详细信息.
你更喜欢哪个?为什么?
小智 5
还有另一种选择 - 使用COALESCE在T-SQL查询中指定规则或使用null-coalescing运算符?在你的代码中(也适用于LinqToSQL).
其中任何一个只需要一次调用数据库,因此选项1为+1.