日期:2014-05-17  浏览次数:21064 次

关于distinct+union all代替union
例如有多个union 会不会造成多次过滤
SQL code

select username from tab1
union
select username from tab2
union
select username from tab3
...
union
select username from tabn


union 是每次都去除重复行还是别的?
SQL code

select distinct username from (
select username from tab1
union all
select username from tab2
union all
select username from tab3
...
union all
select username from tabn
)


好像只是过滤一次,效率会高吗

------解决方案--------------------
如果只是考虑这两段代码的效率的话,我想第二个会高一些。
------解决方案--------------------
distinct + union all
好些!
------解决方案--------------------
测试了下,测试的结果如下
SQL code
SQL> select  tbrq from dbscgs_mx
  2  union
  3  select  tbrq from dbscgs_mxbak
  4  union
  5  select  trunc(lrrq) from dbscgs_mx
  6  union
  7  select  trunc(lrrq) from dbscgs_mxbak;
......
已选择57行。

实际:187

select distinct rq from
(select tbrq rq from dbscgs_mx
union all
select tbrq rq from dbscgs_mxbak
union all
select trunc(lrrq) rq from dbscgs_mx
union all
select trunc(lrrq) rq from dbscgs_mxbak);
......

已选择57行。

实际:171