oracle的一些零碎整理
1.有时候处理数据库时,一不小心脑子一热,操作了某些不该执行的语句,
然后得麻烦了, 其实每天第一件事,不是急着操作数据库,而是做好准备
工作设置一条回滚语句(即反悔语句)
然后得麻烦了, 其实每天第一件事,不是急着操作数据库,而是做好准备
工作设置一条回滚语句(即反悔语句)
设置语句:savepoint aa;
回滚语句:rollback to aa;
2.oracle表的默认格式,不是我们遵循的那种模式,就需要修改表中的日期的默认格式
语句:alter session set nls_date_format='yyyy-mm-dd';
3.查询不包涵重复的数据
语句:select distinct(关键字) table.列名 from table(表名);
4.解决计算时有空值的问题
oracle计算时,如果有一个数位空时,则计算的结果都为空
解决方法:使用nvl(列名,0)函数解决
例:select distinct e.sal*12+nvl(e.comm,0) as "年工资",e.ename from emp e;
5.oracle表的复杂查询
①如果在select语句同时包含有group by,having ,order by 那么他们的顺序是
group by,having ,order by
②在选择列表中如果有列、表达式、和分组函数,那么这些列和表达式必须有一个
出现在group by 子句中,否则就会报错
例:select deptno,avg(sal),max(sal) fro emp group by deptno having avg(sal) < 2000;
6.多行子查询
多行子查询返回多行数据的子查询(多行子查询只能使用'in'不能使用'=')
例:查询和部门号10的工作的雇员的名字、岗位、工资、部门号
select e.ename,e.job,e.sal,e.deptno from emp e
where e.job in(select e.job from emp e where e.deptno ='10');
7.多列子查询
多列子查询则是值查询返回多个列数据的子查询语句
例:查询与smith的部门和岗位完全相同的所有雇员
select * from emp where (deptno,job)=(select deptno,job from emp e where ename='SMITH');
8.oracle给表取别名不能加as,给列名加别名可以加as
9.oracle分页,一共有3种方式
①rownum分页
(select * from emp)
②显示rownum[oracle分配的]
select e.*,rownum as ru from (select * from emp ) e;
③查询前N行的记录
例:前五行的记录
select * from (select e.*,rownum as ru from (select * from emp ) e where rownum <= 10) where rownum <= 5;
10.分页:查找第五行到第十行之间的记录
select * from (select e.*,rownum rn from (select * from emp) e where rownum <=10) where rn <= 5;
11.用查询结果创建新表
create table mytable(ename,job,mgr,sal) select e.ename,e.job,e.mgr,e.sal
from emp e;
回滚语句:rollback to aa;
2.oracle表的默认格式,不是我们遵循的那种模式,就需要修改表中的日期的默认格式
语句:alter session set nls_date_format='yyyy-mm-dd';
3.查询不包涵重复的数据
语句:select distinct(关键字) table.列名 from table(表名);
4.解决计算时有空值的问题
oracle计算时,如果有一个数位空时,则计算的结果都为空
解决方法:使用nvl(列名,0)函数解决
例:select distinct e.sal*12+nvl(e.comm,0) as "年工资",e.ename from emp e;
5.oracle表的复杂查询
①如果在select语句同时包含有group by,having ,order by 那么他们的顺序是
group by,having ,order by
②在选择列表中如果有列、表达式、和分组函数,那么这些列和表达式必须有一个
出现在group by 子句中,否则就会报错
例:select deptno,avg(sal),max(sal) fro emp group by deptno having avg(sal) < 2000;
6.多行子查询
多行子查询返回多行数据的子查询(多行子查询只能使用'in'不能使用'=')
例:查询和部门号10的工作的雇员的名字、岗位、工资、部门号
select e.ename,e.job,e.sal,e.deptno from emp e
where e.job in(select e.job from emp e where e.deptno ='10');
7.多列子查询
多列子查询则是值查询返回多个列数据的子查询语句
例:查询与smith的部门和岗位完全相同的所有雇员
select * from emp where (deptno,job)=(select deptno,job from emp e where ename='SMITH');
8.oracle给表取别名不能加as,给列名加别名可以加as
9.oracle分页,一共有3种方式
①rownum分页
(select * from emp)
②显示rownum[oracle分配的]
select e.*,rownum as ru from (select * from emp ) e;
③查询前N行的记录
例:前五行的记录
select * from (select e.*,rownum as ru from (select * from emp ) e where rownum <= 10) where rownum <= 5;
10.分页:查找第五行到第十行之间的记录
select * from (select e.*,rownum rn from (select * from emp) e where rownum <=10) where rn <= 5;
11.用查询结果创建新表
create table mytable(ename,job,mgr,sal) select e.ename,e.job,e.mgr,e.sal
from emp e;