您的位置:首页 > 数据库 > Oracle

oracle 四种集合运算

2014-06-02 11:44 786 查看
oracle 支持4种集合运算符: union , union all , minus , intersect

union 返回来自所有输入查询的不包含重复值的结果集。

union all 返回两个集合中的所有行,包含重复。

minus 将第一个查询的结果集作为基础数据集减去另一个查询结果集。 通常代替not exists (反联结)

意思是:我需要返回在数据行源A中存在但是在B中不存在的数据行集。

intersect 返回在所有输入查询中都存在的唯一行集。通常代替exists(半联结)

意思是:我需要返回源A和B中都存在的数据行集合

</pre><pre name="code" class="plain">SQL> select color from table1;  测试表1

COLOR
----------
RED
RED
ORANGE
ORANGE
ORANGE
YELLOW
GREEN
BLUE
BLUE
VIOLET

10 rows selected.

SQL> select color from table2; 测试表2

COLOR
----------
RED
RED
BLUE
BLUE
BLUE
GREEN

6 rows selected.

SQL> select color from table3; 测试表3

SQL> select color from table1 union   union 去除重复行
  2  union
  3  select color from table2;

COLOR
----------
BLUE
GREEN
ORANGE
RED
VIOLET
YELLOW

6 rows selected.

SQL> select color from table1   union all 不会去除重复行
  2  union all
  3  select color from table2;

COLOR
----------
RED
RED
ORANGE
ORANGE
ORANGE
YELLOW
GREEN
BLUE
BLUE
VIOLET
RED
RED
BLUE
BLUE
BLUE
GREEN

16 rows selected.

SQL> select color from  table1  union 与空表进行集合运算
  2  union
  3  select color from table3
  4  ;

COLOR
----------
BLUE
GREEN
ORANGE
RED
VIOLET
YELLOW

6 rows selected.

SQL> select color from table1   table1 减去table2
  2  minus
  3  select color from table2;

COLOR
----------
ORANGE
VIOLET
YELLOW

SQL> select color from table2
  2  minus
  3  select color from table1;

no rows selected

SQL> select color from table1    table1和table2都存在的行
  2  intersect
  3  select color from table2;

COLOR
----------
BLUE
GREEN
RED
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: