SELECT--UNION,UNION ALL,MINUS, INTERSECT,EXISTS

SELECT--UNION,UNION ALL,MINUS, INTERSECT
返回两个查询结果的集合操作,两个查询结果集必须字段相同。
UNION和UNION ALL并集操作,UNION并集后去掉重复结果,UNION ALL直接并集
MINUS差集操作
INTERSECT交集操作
SQL> select * from dept2;

DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
88 TEST CHINA
SQL> select * from dept;

DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
SQL> SELECT * FROM DEPT UNION SELECT * FROM DEPT2;

DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
88 TEST CHINA

SQL> SELECT * FROM DEPT UNION ALL SELECT * FROM DEPT2;

DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
88 TEST CHINA

已选择9行。
SQL> SELECT * FROM DEPT MINUS SELECT * FROM DEPT2;

未选定行

SQL> SELECT * FROM DEPT2 MINUS SELECT * FROM DEPT;

DEPTNO DNAME LOC
---------- -------------- -------------
88 TEST CHINA

SQL> SELECT * FROM DEPT2 INTERSECT SELECT * FROM DEPT;

DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
====================================================
使用EXISTS(NOT EXISTS)替换IN(NOT IN)
IN(NOT IN)在执行数据库操作时性能非常低下,应该使用EXISTS(NOT EXISTS)替换,特别是NOT IN子句将执行一个内部的排序和合并;
EXISTS子查询使用主表的字段限制查询数据
SELECT *
FROM SCOTT.EMP E
WHERE EXISTS (SELECT * FROM SCOTT.DEPT WHERE DEPT.DEPTNO = E.DEPTNO AND DEPTNO = 20);
--因为EXISTS可以看到外表,所以,如果表名重复,使用表别名区分,在子查询中一定写清楚和外表的关联关系,另外,子查询写SELECT * 是对的,不用写字段名。

上一篇:21、bootstrap框架


下一篇:java.lang.UnsatisfiedLinkError: C:\apache-tomcat-8.0.21\bin\tcnative-1.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform