我有三个表,其中两个表有1对多的关系(表A和B),第三个是LookUp表(表LU)。我想拉出状态(在两个表上)<>的所有记录' d'
在我的情况表A中没有状态='但是,表B的所有相关记录都具有状态=' D'。所以我需要做的是从表A中提取一条记录而不从表B中提取(因为它没有任何有效的相关记录)。
这是我的查询,它在我描述的场景中没有返回任何内容:
scheduler
我尝试了SELECT A.Field1,
A.Field2,
A.KeyField1,
LU.LookUpField,
B.Field1,
B.Field2,
FROM TableA A
LEFT OUTER JOIN TableB B ON A.KeyField1 = B.KeyField1
AND A.KeyField2 = B.KeyField2
JOIN LookUpTable LU ON LU.FieldID = B.FieldID
WHERE A.KeyField = '11111'
AND ISNULL(A.Status, SPACE(0)) <> 'D'
AND ISNULL(B.Status, SPACE(0)) <> 'D'
ORDER BY A.KeyField, LU.SortOrder
,当表B没有有效数据时,我只会带回空白字段。但是当两个表中的记录都有有效数据时,我带回了额外的行,其中包含我在第一个场景中不想要的空白字段。
答案 0 :(得分:0)
LEFT OUTER JOIN TableB B ON A.KeyField1 = B.KeyField1
AND A.KeyField2 = B.KeyField2
JOIN LookUpTable LU ON LU.FieldID = B.FieldID
WHERE A.KeyField = '11111'
AND ISNULL(A.Status, SPACE(0)) <> 'D'
AND ISNULL(B.Status, SPACE(0)) <> 'D'
到
LEFT OUTER JOIN TableB B ON A.KeyField1 = B.KeyField1
AND A.KeyField2 = B.KeyField2
AND ISNULL(B.Status, SPACE(0)) <> 'D'
JOIN LookUpTable LU ON LU.FieldID = B.FieldID
WHERE A.KeyField = '11111'
AND ISNULL(A.Status, SPACE(0)) <> 'D'