您的位置:首页 > 数据库 > Oracle

ORACLE 学习笔记第二天

2017-01-17 00:00 316 查看
一、子查询

多表查询主要解决的问题是不能一步求解的查询.

1. 可以在select,where,having,from后面放置子查询

在select语句之后放置子查询:

select empno,ename,sal,(select job from emp where empno=7839) 第四列 from emp;



2.不可以在group by 后面放置子查询

3. 强调from后面的子查询

select *from (select empno,ename sal from emp);



4.主查询与字查询可以不是同一张表,只要子查询返回的结果主查询可以使用即可

--查询部门名称是SALES的员工信息

select * from emp where deptno=(select deptno from dept where dname='SALES');



--上述查询也可以用多表查询完成。

select e.* from emp e,dept d where e.deptno=d.deptno and d.dname='SALES';





5.子查询与in

--查询部门名称是SALES和ACCOUNTING的员工

select * from emp where deptno in(select deptno from dept where dname='SALES' or dname='ACCOUNTING'); ---子查询形式

select e.* from emp e,dept d where e.deptno=d.deptno and (d.dname='SALES' or d.dname='ACCOUNTING'); ---多表查询形式

6.子查询与any any是与集合中的任意一个值比较

--查询工资比30号部门任意一个员工高的员工信息

select * from emp where sal>any(select sal from emp where deptno=30);

select * from emp where sal>(select min(sal) from emp where deptno=30);

7.子查询与all all是与集合中的所有值比较

--查询工资比30号部门所有员工高的员工信息

select * from emp where sal>all(select sal from emp where deptno=30);

select * from emp where sal>(select max(sal) from emp where deptno=30);

8.多行子查询中的null

not in(A,B,NULL) 中不可以含有null 因为这个分解了是and A and B AND NULL 的条件

in(A,B,NULL) 中可以含有null 因为这个分解了是 OR A OR B OR NULL

二、集合运算

集合运算指的是两个集合的交集并集之类的运算。

1.union 并集运算,返回两个集合去掉重复元素的所有记录。

查询部门号为10和20 的员工信息

select * from emp where deptno=10 union select * from emp where deptno=20;

2. 使用union 完成rollup函数查询的报表格式数据

select deptno,job,sum(sal) from emp group by deptno job

union

select deptno,sum(sal) from emp group by deptno

union

select sum(sal) from emp;

注意事项:a.这个查询是错误的,因为union运算符链接的两个查询集合需要列数相同和类型一致。

b.采用第一个集合表头作为最后表头。

c. order by 永远放在最后

select deptno,job,sum(sal) from emp group by deptno job

union

select deptno,to_char(null),sum(sal) from emp group by deptno

union

select to_number(null),to_char(null), sum(sal) from emp;



三、练习题

数据表本身不存在的列,数据库为了数据更具观赏性而提供的本身不存在的列。

1. rownum 行数

select rownum,ename,sal from emp;



注意:rownum 用作条件时,只能使用 < <=,不能使用 > >= 猜测:这个和它的序号生成有关。假如条件时>=3 ,那么行号只能写4.5.6...

2. 获取按薪水降序排列的5-8条记录。

select * from (select rownum r,e1.* from (select * from emp order by sal) e1 where rownum<=8) where r>=5;



3. 获取薪水比部门平均薪水高的员工信息

select e.ename,e.deptno,e.sal,d.avgsal from emp e,(select deptno,avg(sal) avgsal from emp group by deptno) d where e.deptno=d.deptno and e.sal>d.avgsal;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: