在SQL Server中,我需要在一列中选择具有特定值的行,但是如果它们在其他2个表中具有特定值,则必须接受这些记录并将其从结果中排除。我想要的记录可能不存在于其他2个表中。
{
"stage" : "FETCH",
"filter" : {
"$and" : [
{
"d" : {
"$eq" : 4
}
},
{
"a" : {
"$eq" : 1
}
},
{
"b" : {
"$eq" : 2
}
}
]
},
"inputStage" : {
"stage" : "AND_SORTED",
"inputStages" : [
{
"stage" : "IXSCAN",
"keyPattern" : {
"d" : 1
},
"indexName" : "d_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"d" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"d" : [
"[4.0, 4.0]"
]
}
},
{
"stage" : "IXSCAN",
"keyPattern" : {
"a" : 1
},
"indexName" : "a_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"a" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"a" : [
"[1.0, 1.0]"
]
}
}
]
}
}
我一直在获取ID确实出现在Table2但不是Table3的记录,反之亦然。我想要做的是在表2中使用Column2 =' X'中排除该ID。或表3与Column3 =' Y'
我认为我的逻辑或语法是错误的。
另外我知道"不在"如果子查询的结果包含NULL,可以做一些奇怪的事情,所以我不确定是否有更简单的方法来执行此操作。
我已经用一堆不同的方式重写了这一点,但我没有得到我想要的结果。我一直没有记录,记录太少或记录太多......唉!
有什么建议吗?
答案 0 :(得分:2)
您需要更改为OR
:
SELECT Table1.ID
FROM Table1
WHERE Table1.Column1 = 'A'
AND (
Table1.ID NOT IN (SELECT Table2.ID FROM Table2 WHERE Table2.Column2 = 'X')
OR
Table1.ID NOT IN (SELECT Table3.ID FROM Table3 WHERE Table3.Column3 = 'Y'))
或者您可以将其重写为:
SELECT Table1.ID
FROM Table1
WHERE Table1.Column1 = 'A'
EXCEPT (
SELECT Table2.ID FROM Table2 WHERE Table2.Column2 = 'X'
UNION ALL
SELECT Table3.ID FROM Table3 WHERE Table3.Column3 = 'Y'
)
修改强>
SELECT DISTINCT Table1.ID
FROM Table1
LEFT JOIN Table2
ON Table1.ID = Table2.ID
AND Table2.Column2 = 'X'
LEFT JOIN Table3
ON Table1.ID = Table3.ID
AND Table3.Column3 = 'Y'
WHERE Table1.Column1 = 'A'
AND (Table2.ID IS NULL AND Table3.ID IS NULL);