我很难搞清楚这个问题。我需要来自issueMaster的记录基于userId和visible,加入到可见的issueActionDetails,但可能没有任何issueActionDetails。我只是遇到了有问题的问题。
SELECT
b.AssignedTo,
b.Visible,
c.ONEKEY_ID,
C.PHYS_NAME[Doctor],
B.IssueDescription[Issue to Address],
CASE WHEN A.ActionDescription IS NULL THEN 'To Be Assigned' ELSE A.ActionDescription END as [Action],
CASE WHEN A.AssignedTo IS NULL THEN 'To Be Assigned' ELSE A.AssignedTo END as [Assigned To],
CASE WHEN D.[Description] IS NULL THEN 'To Be Assigned' ELSE D.[Description] END As [Status]
FROM [dbo].[tbl_IssueMaster] B
LEFT JOIN [dbo].[tbl_IssueActionDetails] A ON A.IssueID =B.IssueID
INNER JOIN [dbo].[tbl_DoctorsNew] C ON B.OnekeyID =C.ONEKEY_ID
INNER JOIN [dbo].[Action_Status] D ON A.ActionStatus = D.ID
WHERE B.AssignedTo = @UserId AND B.Visible =1 AND A.Visible =1
ORDER BY c.ONEKEY_ID,B.DisplayOrder ,A.DisplayOrder
答案 0 :(得分:1)
"外在"对tbl_IssueActionDetails的连接被两件事否定了:
Action_Status
的内部联接:
INNER JOIN [dbo].[Action_Status] D ON A.ActionStatus = D.ID
WHERE子句中的谓词
AND A.Visible =1
对于tbl_IssueActionDetails
中没有匹配行的任何返回行,该表的列中的值都将为NULL。 (数据库本质上是从tbl_IssueActionDetails
创建一个由所有NULL组成的行,并且"匹配"该行从左侧表中的行开始。
从该表中的列中排除NULL值的任何谓词都将排除该行。如果我们指定仅返回" A.Visible=1
"的行,那将排除该列中具有NULL值的任何行。当我说"外在"时,我的意思是什么? LEFT JOIN操作被否定了。
修复方法是将谓词移动到ON
tbl_IssueActionDetail
子句
并将INNER JOIN
更改为外部联接LEFT JOIN
答案 1 :(得分:0)
LEFT JOIN [dbo].[tbl_IssueActionDetails] A
ON A.IssueID = B.IssueID
AND A.Visible = 1
从where子句中删除“AND A.Visible = 1”,将其添加为连接条件
OR,更改where子句以允许LEFT JOIN的空条件
WHERE B.AssignedTo = @UserId
AND B.Visible = 1
AND ( A.Visible = 1 OR A.Visible IS NULL)
如果你总是坚持在where子句中使用A.Visible = 1来抑制LEFT JOIN可以提供的NULL。无论何时使用外连接,请保持警惕。