Oracle数据库之集合运算
集合運(yùn)算符
集合運(yùn)算符查詢組合兩個(gè)組件查詢的結(jié)果到一個(gè)結(jié)果,包含集合運(yùn)算符的查詢稱為復(fù)合查詢。SQL集合運(yùn)算符如下:
集合運(yùn)算符
UNION:All distinct rows selected by either query
UNION ALL:All rows selected by either query, including all duplicates
INTERSECT:All distinct rows selected by both queries
MINUS:All distinct rows selected by the first query but not the second
SQL> 查詢10和20號(hào)部門的員工
SQL> 1. select * from emp where deptno in (10,20);
SQL> 2. select * from emp where deptno=10 or deptno=20;
SQL> 3. 集合運(yùn)算
SQL> select * from emp where deptno=10
SQL> 加上
SQL> select * from emp where deptno=20
SQL> select * from emp where deptno=10
2 union
3 select * from emp where deptno=20;
SQL> select deptno,job,sum(sal) from emp group by rollup(deptno,job);
DEPTNO JOB SUM(SAL) ---------- --------- ---------- 10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 10 8750 20 CLERK 1900 20 ANALYST 6000 20 MANAGER 2975 20 10875 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600 DEPTNO JOB SUM(SAL) ---------- --------- ---------- 30 9400 29025SQL> 注意的問(wèn)題
SQL> 1. 參與運(yùn)算的各個(gè)集合必須列數(shù)相同,且類型一致
SQL> 2. 采用第一個(gè)集合作為最后的表頭
SQL> 3. order by永遠(yuǎn)在最后
SQL> 4. 括號(hào)
SQL> select deptno,job,sum(sal) from emp group by deptno,job
2 union
3 select deptno,to_char(null),sum(sal) from emp group by deptno
4 union
5 select to_number(null),to_char(null),sum(sal) from emp;
測(cè)試集合運(yùn)算和聚合函數(shù)的效率
SQL> --打開(kāi)SQL執(zhí)行時(shí)間的開(kāi)關(guān)
SQL> set timing on
SQL> select deptno,job,sum(sal) from emp group by rollup(deptno,job);
SQL> select deptno,job,sum(sal) from emp group by deptno,job
2 union
3 select deptno,to_char(null),sum(sal) from emp group by deptno
4 union
5 select to_number(null),to_char(null),sum(sal) from emp;
//關(guān)閉時(shí)間開(kāi)關(guān)
SQL> set timing off
結(jié)論:盡量少使用集合運(yùn)算。
總結(jié)
以上是生活随笔為你收集整理的Oracle数据库之集合运算的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Oracle数据库之子查询
- 下一篇: Oracle数据库之数据处理