SQL-联合所有和除外

SQL-Union ALL and Except

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

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

(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

这就是您的查询 returns。

这在documentation中有解释:

If EXCEPT or INTERSECT is used together with other operators in an expression, it is evaluated in the context of the following precedence:

  1. Expressions in parentheses

  2. The INTERSECT operator

  3. EXCEPT and UNION evaluated from left to right based on their position in the expression