oracle中怎么区分union与union all的使用

oracle中如何区分union与union all的使用
oracle中如何区分union与union all的使用

union 对两个结果集进行并集操作,不包括重复行,同时进行默认规则排序;

union all 对两个结果集进行并集操作,包括重复行,不进行排序


union all 要比union快很多,所以,如果可以确认合并的两个结果集中不包含重复的数据的话,那么就使用union all,如下:

尽量使用union all,因为union需要进行排序,去除重复记录,效率低
union
如果表有多个索引列的时候,用union 替换 where 中的or 效率会提高不少。索引列使用or会造成全表扫描。如果有column 没有使用索引,就得记得or了。

    select date from store_information
    union
    select date from internet_sales

注意:union用法中,两个select语句的字段类型匹配,而且字段个数要相同,如上面的例子,在实际的软件开发过程,www.3ppt.com会遇到更复杂的情况,具体请看下面的例子

    select '1' as type,fl_id,fl_code,fl_cname,flda.fl_parentid from flda
    where zt_id=2006030002
    union
    select '2' as type,xm_id,xm_code ,xm_cname ,fl_id from xmda
    where exists (select * from (select fl_id from flda where zt_id=2006030002 ) a where xmda.fl_id=a.fl_id)
    order by type,fl_parentid ,fl_id

这个句子的意思是将两个sql语句union查询出来,查询的条件就是看xmda表中的fl_id是否和主表flda里的fl_id值相匹配,(也就是存在).



union all 详细实例

union 指令的目的是将两个 sql 语句的结果合并起来,可以查看你要的查询结果.

例如:



    sql>   select   *   from   a;

    id                   name
    ----------   ----------
    1                     aa
    2                     bb
    3                     cc
    6                     dd
    7                     ee

    sql>   select   *   from   b;

    id                   addr
    ----------   ----------
    1                     aa
    2                     bb
    3                     cc
    4                     dd
    5                     ee

    sql>   select   *   from   a
        2     union   all
        3     select   *   from   b;

    id                   name
    ----------   ----------
    1                     aa
    2                     bb
    3                     cc
    6                     dd
    7                     ee
    1                     aa
    2                     bb
    3                     cc
    4                     dd
    5                     ee

    已选择10行。

    sql>   select   *   from   a
        2     union 
        3     select   *   from   b;

    id                   name
    ----------   ----------
    1                     aa
    2                     bb
    3                     cc
    4                     dd
    5                     ee
    6                     dd
    7                     ee

已选择7行。

sql>

注意:union用法中,两个select语句的字段类型匹配,而且字段个数要相同,如上面的例子,在实际的软件开发过程,会遇到更复杂的情况