0

我在下面有这个查询,它工作正常,我得到了我需要的东西。我需要知道的是,这是编写此查询的正确方法,还是有任何方法可以缩短它?

我有 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 行的查询吗?提前谢谢你们:)

4

1 回答 1

3

不,您不能,您在结果集中使用D,EF,因此您必须加入这些表。D.FullName AS CallOpenedBy如果您从结果中删除了and之类的内容,则只能删除它们。E.FullName AS
EngineerName
F.FullName AS CallClosedBy


作为旁注(我敢打赌你问这个问题的最初原因),但是如果呼叫尚未结束并且A.CallClosedBy尚未分配给F.UserProID该行中的值,则将从结果中排除。

LEFT OUTER JOIN如果它们链接的 3 个列中的任何一个在目标表中可能没有相应的记录或可能为空,则您应该使用这 3 个表。

这是我会怎么做

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)在输出中显示而不是排除该行。

于 2012-12-17T04:44:59.543 回答