3

当我在 SQL 中执行 except 和 union 语句时,我看到了一种奇怪的行为。

我有两张桌子

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 行,因为并非所有列都相同。

4

1 回答 1

7

您似乎认为查询被解释为:

(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

这是您的查询返回的内容。

这在文档中进行了解释:

如果 EXCEPT 或 INTERSECT 与表达式中的其他运算符一起使用,则在以下优先级的上下文中对其进行评估:

  1. 括号中的表达式

  2. INTERSECT 运算符

  3. EXCEPT 和 UNION 根据它们在表达式中的位置从左到右求值

于 2018-08-01T20:01:18.543 回答