Oracle【序列、索引、视图、分页】

1、Oracle序列
语法:create sequence 序列名
 特点1:默认是无值,指针指向没有值的位置
 特点2:序列名.nextval 每次执行值会自增一次,步长为 1
 特点3:序列名.currval查看当前序列的值。[默认是没有,需要创建再执行先]
作用:作为主键使用,动态的获取主键的值,这样新增数据的时候的避免了主键冲突
  --使用的是 序列名.nextval作为主键
注意:主键是非空唯一,不需要主键的值是连续的值,不重复即可

1 --创建默认序列
2 create sequence cc;--创建序列
3 select cc.nextval from dual;--递增的方式去创建序列
4 select cc.currval from dual;--查询当前序列 
 1 --创建测试表
 2 create table student(
 3      tid number(10) primary key,
 4       tname varchar(100) not null
 5       )
 6 --添加测试数据
 7 --之前写法:【多复制多改动很多数据,费时间】
 8 insert into student values(1,'迪丽热巴');
 9 insert into student values(2,'柚子解说');
10 --使用序列添加
11 insert into student values(cc.nextval,'迪丽热巴');
12 insert into student values(cc.nextval,'柚子解说');
1 --创建自定义序列
2 create sequence c1--创建序列
3 start with 5 --设置开始位置
4 increment by 2 --设置步长
5 select c1.nextval from dual
6 select c1.currval from dual
7 --删除序列:drop sequence 序列名
8 drop sequence cc;

2、Oracle索引
作用:提升查询效率,处理大量的数据才会发现索引的强大之处
--特点:显示的创建,隐式的执行
--注意:oracle会自动给表的主键创建索引。[一般是编号,学号等]
使用索引:【创建、删除】

1 --创建语法
2 create index 索引名 on 表名(字段名)
3 --测试数据
4 create index index_student_tname on student(tname)--创建索引
5 select * from student where tname='柚子解说'
6 --删除索引
7 drop index index_student_tname

3、Oracle视图
使用视图:【创建、删除】
创建视图: create view 视图名 as select 对外提供的内容 from 真实表名 
删除视图: drop view 视图名 
视图特点:
 特点1:保护真实表,隐藏重要字段的数据。保护数据。
 特点2:在视图中的操作会映射执行到真实表中
 特点3:可以手动开启只读模式 使用关键字 with read only
注意:视图的创建用户必须具有DBA权限

1 --测试视图
2 --创建视图并对外提供了sid,sname,ssex三个字段
3 create view stu as select sid,sname,ssex from student
4 select * from student--可查询所有的详细数据
5 select * from stu--只能查询到视图对外开放的字段

--视图的只读模式
create view stu2 as select sid,sname,ssex from student with read only 

4、分页
当一个表中的数据量庞大时,如果数据一次性全部显示给用户,则造成页面过于庞大,体验感low。
使用:rownum 关键字 :--oracle对外提供的自动给查询结果编号的关键字,与数据没有关系。
注意:rownum 关键字只能做< <=的判断,不能进行> >=的判断

1 --查询员工信息前5条数据[第一页]
2 select rownum,e.* from emp e where rownum<=5
3 select * from (select rownum r,e.* from emp e where rownum <=5) t where r>0;

1 --查询员工信息的6-10条后所有数据[第二页]
2 select * from (select rownum r,e.* from emp e where rownum<=10) t where r>5

1 --查询员工信息的11-15条数据[第三页]
2 select * from (select rownum r,e. * from emp e where rownum<=15) t where r>10;


分页的总结:每页显示n条数据,查询第m页数据 
select * from (select rownum r,e. * from 分页的表 e where rownum<=n*m) t where r>n*m-n;

例子:每页显示3条数据,查询第2页的数据
select * from (select rownum r,e. * from emp e where rownum<=3*2) t where r>3*2-3;
select * from (select rownum r,e. * from emp e where rownum<=6) t where r>3;


灵活应变:

1 --只查询员工姓名,工资。【每页显示3条数据,查询第4页的数据】
2 select * from (select rownum r,e. * from emp e where rownum<=3*4) t where r>3*4-3;
3 select t.ename,t.sal from (select rownum r,e. * from emp e where rownum<=12) t where r>9;


1 --分页查询员工信息按照工资排序
2 select * from (select rownum r,t.* from (select * from emp  order by sal desc) t where rownum<=10 ) where r>5



猜你喜欢

转载自www.cnblogs.com/cao-yin/p/9783101.html