我在下面有这个查询,它的工作正常,我得到了我需要的东西。我需要知道的是,这是以正确的方式编写此查询还是有任何方法可以缩短它?
我有4个表,第1个有分支信息,第2个有客户信息,第3个有工程师信息,第4个有服务电话信息。
在服务呼叫表中,3列与3个不同的工程师名称匹配
这是查询
SELECT
B.BranchName, C.Name AS CustomerName,D.FullName AS CallOpenedBy,
A.CallOpenTime, A.CallMode, A.CallType, A.ReportedBy,
A.ReportedVia, A.ReportedProblem,
A.MaterialsReceived, A.MisComments, A.CallPriority, A.EstimatedAmount,
E.FullName AS EngineerName,
A.ActionTaken, A.CallClosedTime,
F.FullName AS CallClosedBy, A.Status,
A.Amount
FROM
TblServiceCalls A
INNER JOIN
TblBranchInfo B ON A.BranchID = B.BranchID
INNER JOIN
TblMainMaster C ON A.MasterID = C.MasterID
INNER JOIN
TblUserProfiles D ON A.CallOpenedBy = D.UserProID
INNER JOIN
TblUserProfiles E ON A.Engineer = E.UserProID
INNER JOIN
TblUserProfiles F ON A.CallClosedBy = F.UserProID
我可以缩短最后3行的查询吗?提前谢谢你们:)
答案 0 :(得分:3)
不,你不能,你在结果集中使用D
,E
和F
,所以你必须加入这些表。如果您从结果中删除了D.FullName AS CallOpenedBy
和E.FullName AS
以及
EngineerNameF.FullName AS CallClosedBy
等内容,则只能将其删除。
作为旁注(并且我打赌您提出此问题的原因),但如果暂停通话并且A.CallClosedBy
尚未分配给F.UserProID
中的值行将被排除在结果之外。
如果他们链接的3列中的任何一列在目标表中没有相应的记录或者可能为null,那么您应该对这3个表使用LEFT OUTER JOIN
。
我将如何做到这一点
Select B.BranchName, C.Name AS CustomerName,IsNull(D.FullName, '(Not Assigned)') AS CallOpenedBy,
A.CallOpenTime,A.CallMode, A.CallType,A.ReportedBy, A.ReportedVia, A.ReportedProblem,
A.MaterialsReceived, A.MisComments,A.CallPriority,A.EstimatedAmount,IsNull(E.FullName, '(Not Assigned)') AS
EngineerName, A.ActionTaken, A.CallClosedTime,IsNull(F.FullName, '(Not Assigned)') AS CallClosedBy, A.Status,
A.Amount From TblServiceCalls A
INNER JOIN TblBranchInfo B ON A.BranchID = B.BranchID
INNER JOIN TblMainMaster C ON A.MasterID = C.MasterID
LEFT OUTER JOIN TblUserProfiles D ON A.CallOpenedBy = D.UserProID
LEFT OUTER JOIN TblUserProfiles E ON A.Engineer = E.UserProID
LEFT OUTER JOIN TblUserProfiles F ON A.CallClosedBy = F.UserProID
现在,如果值为NULL
或目标表中不存在记录,则输出中将显示(Not Assigned)
,而不是排除该行。