Oracle入门第六天(中)——SET运算符(交并差集)

一、概述

  1.SET运算符是什么 

    将多个查询用 SET 操作符连接组成一个新的查询

      UNION/UNION ALL——并集

      INTERSECT——交集

      MINUS——差集(A\B=A中去掉B中也有的元素)

    关于MySQL的交、并、差集,参考http://blog.csdn.net/goodleiwei/article/details/42149567

  2.图解

   

 

二、交集——UNION

   UNION取交集(自动去重,且要求两结果集列可以对应合并)

SELECT * FROM employees1
UNION
SELECT * FROM employees2

 

    UNION ALL不去重:

 

SELECT * FROM employees1
UNION ALL
SELECT * FROM employees2

 

    排序可以采用以下方式:(因为department_id是第11列,故直接写上列数即可)

SELECT * FROM employees1
UNION
SELECT * FROM employees2
ORDER BY 11

    也可以采取再套一层的写法,参考:https://www.2cto.com/database/201210/163404.html

  当然,如果列确实不匹配,可以通过以下形式调整:

 

SELECT department_id, TO_NUMBER(null) 
       location, hire_date
FROM   employees
UNION
SELECT department_id, location_id,  TO_DATE(null)
FROM   departments;

 

SELECT employee_id, job_id,salary
FROM   employees
UNION
SELECT employee_id, job_id,0
FROM   job_history;

 

 

三、交集——INTERSECT

  

SELECT * FROM employees1
INTERSECT
SELECT * FROM employees2

四、差集——MINUS

  

SELECT employee_id,job_id
FROM   employees
MINUS
SELECT employee_id,job_id
FROM   job_history;

 

posted @ 2018-01-07 12:15  ---江北  阅读(496)  评论(0编辑  收藏  举报
TOP