【问题标题】:SQL-Union ALL and ExceptSQL-Union ALL 和 except
【发布时间】:2018-08-01 19:55:56
【问题描述】:

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

【问题讨论】:

    标签: sql union sql-except


    【解决方案1】:

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

    (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中有解释:

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

    1. 括号中的表达式

    2. INTERSECT 运算符

    3. EXCEPT 和 UNION 根据它们在表达式中的位置从左到右进行计算

    【讨论】:

    • 完美,非常感谢。是的,这正是我在解释它,今天学到了一些新东西。不知道那些运营商规则。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多