1 集合运算的规则
当查询中使用了union,union all,intersect和差集操作运算时,必须有相同个数的列,数据类型可以不用完全一样,但是要能够互相转换。
第一个查询语句的列出现在结果集中。除了union all以外,会自动去重,默认按照升序排序。
括号可以用来改变执行的顺序.
2 union和union all 并集
union操作将sql语句中的结果全部输出,而且去重。
取并集的sql语句中必须有相同个数的列,对应列的数据类型必须在相同的数据类型组中(比如numberic 或 character),列的名字可以不一样,union操作对所有的列取并集运算,在检测重复值时空值不会被忽略,默认结果会以升序来显示。
例如:employees和Job_history表有相同的列且对应的列的数据类型一样。
SELECT employee_id, job_id, department_id
FROM employees
UNION
SELECT employee_id, job_id, department_id
FROM job_history;
union all效果和union类似,只不过union all不会去重且不会排序。
3 intersect 交集
返回多个查询语句的交集。多个sql的列的个数和对应列的数据类型一样,对于数据类型能够互相隐式转换也可以,列的名字可以不用一样。修改sql的顺序不会改结果。intersect操作不会忽略空值。
如:
SELECT employee_id, job_id, department_id
FROM employees
INTERSECT
SELECT employee_id, job_id, department_id
FROM job_history;
统计employees和Job_history表的交集。
4 minus差集
minus操作返回第一个查询句中的行,且这些结果没有出现在第二个查询结果集中。(第一个select语句minus第二个select语句)
列的个数必须相同且数据类型必须在同一个数据类型组中,列的名字可以不一样。
5 sql中出现转换函数及常量
必须要保证列的个数和数据类型匹配。
如下为了数据类型匹配使用了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;
第一个sql中department_name为varchar2类型,为了和它匹配,第二个sql中使用了to_char函数,依次类推第一个sql的第三个列和第二个sql的第三个列数据类型匹配。
SELECT employee_id, job_id,salary
FROM employees
UNION
SELECT employee_id, job_id,0
FROM job_history;
以上第一个sql的第三个列为数值类型,和第二个sql的数值0匹配。
6 order by
在查询语句中,order by 在sql中只出现 一次且在最后边。
每个sql不能有单独的order by 子句。
order by 子句只会按照第一个select查询中的列来排序。
默认,会按照第一个select查询中的第一个列升序排序。
7 练习
如下哪两个说法正确:
A.The expressions in the SELECT lists must match in number.
B.Parentheses may not be used to alter the sequence of execution.
C.The data type of each column in the second query must match the data type of its corresponding column in the first query.
D.The ORDER BY clause can be used only once in a compound query, unless a UNION ALL operator is used
【答题小贴士】:
1、以墨天轮文章的形式解析题目并给出答案
2、将墨天轮文章链接发送到此文的评论区




