使用 UNION 操作符
1、显示当前和以前的工作的所有员工的详细信息。每个雇员只显示一次。
select employee_id, job_id
from employees
union
select employee_id, job_id
from job_history;
使用 UNION ALL 操作符
1、显示当前和以前的员工的所有部门。
select employee_id, job_id, department_id
from employees
union all
select employee_id, job_id, department_id
from job_history
order by employee_id;
使用 INTERSECT 操作符
显示员工ID和工作ID,当前的职称相同(也就是说,他们换工作但是现在已经回到以前同样的工作)。
select employee_id, job_id
from employees
intersect
select employee_id, job_id
from job_history;
使用 MINUS 操作符
1、显示员工表中一次都没有改变过工作的的员工ID
select employee_id
from employees
minus
select employee_id
from job_history;
相匹配的 SELECT 语句
使用 UNION 操作符显示location_id,department_name,state_province
当字段在一个或另一个表中不存在,必须匹配上数据类型(使用TO_CHAR函数或其他转换函数)
select location_id, department_name "Department",
to_char(null) "warehouse location"
from departments
union
select location_id, to_char(null) "Department",
state_province
from locations;
使用UNION操作符,显示雇员的ID,工作ID,和所有员工的工资
select employee_id, job_id,salary
from employees
union
select employee_id, job_id,0
from job_history;
集合操作中使用 ORDER BY 子句的注意事项
复合查询中 ORDER BY 子句只能在结束时出现一次
集合操作中每个查询不能有单独的 ORDER BY 子句
ORDER BY 子句中 只能识别第一个 SELECT 查询的列。
默认情况下,第一列的第一个 SELECT 查询使用升序对输出进行排序。
请查询出所有的部门下没有 ST_CLERK 工种的 department_id,要求使用集合操作符
select department_id
from departments
minus
select department_id
from employees
where job_id not like 'ST_CLERK';
2、请使用集合操作符写一条 SQL,查出所有的没有部门坐落的国家的 country_id,country_name
select country_id,country_name
from countries
minus
select l.country_id,c.country_name
from locations l join countries c
on (l.country_id=c.country_id)
join departments d
on d.location_id=l.location_id;
3、请使用集合操作符写一条 SQL,查出部门号在 10,50,20 中的所有的 job_id,department_id,
并以 10,50,20 的排列顺序显示。
select distinct job_id,department_id
from employees
where department_id = 10
union all
select distinct job_id,department_id
from employees
where department_id= 50
union all
select distinct job_id,department_id
from employees
where department_id= 20;
4、请查出所有工作发生过变动,但是多次变动后现在的工作是做的以前做过的工作的员工的employee_id 和 job_id
select employee_id,job_id
from employees
intersect
select employee_id,job_id
from job_history;