码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-09-09 11:20:08      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:os   io   使用   ar   数据   on   c   new   数据库   

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 * 是对的,不用写字段名。

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

标签:os   io   使用   ar   数据   on   c   new   数据库   

原文地址:http://www.cnblogs.com/rusking/p/3961586.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!