我有点不知道为什么下面的sql不会产生任何行。显然,有一个不在b中的id 1,我希望它是输出。我知道我错过了关于工会如何运作的一些基本原则 - 可能是因为第二次减去没有输出的事实?
红移:
WITh a as
(select 1 id union all select 2
)
,b as (select 2 id)
select * from a
minus
select * from b
union all
select * from b
minus
select * from a
甲骨文 -
WITh a as
(select 1 id from dual union all select 2 from dual
)
,b as (select 2 id from dual)
select * from a
minus
select * from b
union all
select * from b
minus
select * from a
答案 0 :(得分:2)
编写查询的方式存在操作顺序问题。如果将union的两边包装为子查询,并从中进行选择,那么您将获得预期的结果:
select * from
(select * from a
minus
select * from b ) t1
union all
select * from
(select * from b
minus
select * from a ) t2
似乎正在发生的事情是,首先运行以下内容,让我们留下id=1
:
select * from a
minus
select * from b
然后,此结果与b
:
(select * from a
minus
select * from b)
union all
select * from b
此时,结果集再次包含1和2。但现在,我们对表a
采取减号操作:
(select * from a
minus
select * from b
union all
select * from b)
minus
select * from a
这会产生一个空集,因为(1,2)
减去(1,2)
会让我们一无所获。