SQL-Union ALL 和 except

标签 sql union sql-except

当我在 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:

  1. Expressions in parentheses

  2. The INTERSECT operator

  3. 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/

相关文章:

SQL 处理电话号码字段中的垃圾

mysql - Sql 将 4 个表列与 1 个连接

sql - 如何在没有ORDER BY的情况下订购UNION中的条目?

mysql - 如果 1 列不在结果中,则追加到 MySQL 结果

java - 如何使用一个 SQL 查询从一个独立排序的表中合并两个结果集?

sql - INTERSECT 和 INNER JOIN 之间有根本区别吗?

SQL,仅组合两个具有不同值的表(仅基于三个字段,而不是整行)

sql - Oracle 中的 EXCEPT 关键字

mysql - 显示列中字符串值的一部分的 SQL 查询

c# - 在不知道类型是什么的情况下调用返回泛型集合的泛型方法? C#