当我在 SQL 中执行 except 和 union 语句时,我看到了一个奇怪的行为。
我有两张 table
Select * from #old
数据看起来像这样
oid1 oid2 co
1 11 1
2 22 1
3 33 1
4 55 1
Select * from #new
nid1 nid2 co
1 11 3
2 22 1
3 33 1
4 44 1
4 55 1
这是我的最终查询
Select * from #old
except
Select * from #new
union all
Select * from #new
except
Select * from #old
并给出这些记录
oid1 oid2 co
1 11 3
4 44 1
我的问题是..从第一个except子句开始,这里不应该有另一行:
Select * from #old
except
Select * from #new
这是
oid1 oid2 co
1 11 1
最终查询不应该有 3 行而不是只有 2 行,因为并非所有列都相同。
最佳答案
您似乎认为查询被解释为:
(Select * from #old
except
Select * from #new
)
union all
(Select * from #new
except
Select * from #old
)
但不是。它被解释为:
((Select * from #old
except
Select * from #new
)
union all
Select * from #new
)
except
Select * from #old
这相当于:
Select * from #new
except
Select * from #old
这就是您的查询返回的内容。
这在 documentation 中有解释:
If EXCEPT or INTERSECT is used together with other operators in an expression, it is evaluated in the context of the following precedence:
Expressions in parentheses
The INTERSECT operator
EXCEPT and UNION evaluated from left to right based on their position in the expression
关于SQL-Union ALL 和 except,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51641358/