为什么这个sql使用union all都没有返回数据

时间:2014-04-16 14:45:58

标签: sql oracle union

sql 1st的结果:

select p1.t1, p2.t2, p2.t3 from 
(select 'A' as t1,'' as t2,'' as t3 from dual ) p1 left join
(select '' as t1, '' as t2, '' as t3 from dual where 1=2) p2 on p1.t1 = p2.t1

A   NULL    NULL

sql 2nd的结果:

select p1.t1, p2.t2, p2.t3 from 
(select 'B' as t1,'' as t2,'' as t3 from dual ) p1 left join
(select '' as t1, '' as t2, '' as t3 from dual where 1=2) p2 on p1.t1 = p2.t1

B   NULL    NULL

如果我将所有这两部分sql联合起来,我期望的sql是:

A    NULL    NULL
B    NULL    NULL

但我没有结果。

sql如下所示:

select p1.t1, p2.t2, p2.t3 from 
(select 'A' as t1,'' as t2,'' as t3 from dual ) p1 left join
(select '' as t1, '' as t2, '' as t3 from dual where 1=2) p2 on p1.t1 = p2.t1
union all
select p1.t1, p2.t2, p2.t3 from 
(select 'B' as t1,'' as t2,'' as t3 from dual ) p1 left join
(select '' as t1, '' as t2, '' as t3 from dual where 1=2) p2 on p1.t1 = p2.t1

我在oracle上测试了这个sql。 我想知道为什么结果不像我预期的那样。 顺便说一句,如果使用union而不是union all,结果就像预期一样。

1 个答案:

答案 0 :(得分:2)

你还没有说过你正在遇到哪个版本,但是Gordon Linoff在SQL Fiddle上重现了11.2.0.2,并且正如其他人所说的那样在10g和11.2.0.3中没有看到它,所以这似乎是合理的认为你可能也在11.2.0.2。

在这种情况下,这看起来与错误12336962相同。如果您有权访问Oracle支持,您(或您的DBA)可以查看,但我无法重现它在这里所说的内容,即使它是已发布的错误。运行查询和错误报告中的示例会产生相同的结果,在这两种情况下,从union all更改为union都会产生正确的结果。您可能希望提出服务请求以获得确认。

在11.2.0.3补丁集中修复了这个错误 - 我不确定我是否真的应该分享它,but it's already published here - 所以修补可能是你最好的选择,Oracle可能会建议如果你确实提出了SR。如有疑问,请直接询问Oracle。