Oracle的序列学习
创建序列
使用:create sequence 序列名
特点:
- 默认开始是没有值的,也就是指针指在了没有值的位置
- 序列名.nextval每次执行都会自增一次,默认步长为1
- 序列名.currval查看当前序列的,开始是没有的
作用:作为主键使用,动态的获取主键的值,新增数据时避免了主键冲突,使用的是序列名.nextval作为主键
注意:主键是非空唯一就可以,不需要主键的值是连续的值
--创建默认序列 create sequence cc; --创建序列cc select cc.currval from dual; --查看序列当前值 select cc.nextval from dual; --查看序列自增后的值--创建自定义序列 create sequence aa start with 5 --设置序列从5开始 increment by 2; --设置序列步长为2 select aa.currval from dual; select aa.nextval from dual; --创建测试表 create table teacher( tid number(10) primary key, tname varchar2(100) not null ); insert into teacher values(cc.nextval,'张三'); insert into teacher values(cc.nextval,'李四'); insert into teacher values(cc.nextval,'王五'); insert into teacher values(cc.nextval,'赵六'); select * from teacher; drop table teacher;
删除序列
drop sequence 序列名
drop sequence aa;drop sequence cc;
索引
作用:提升查询效率
使用:
- 创建索引:create index 索引名 on 表名(字段名)
- 删除索引:drop index 索引名
特点:显示的创建,隐式的执行
注意:Oracle或自动给表的主键创建索引
create index index_teacher_tname on teacher(tname); --创建索引drop index index_teacher_tname; --删除索引select * from teacher where tid=8;select * from teacher where tname='张三';
视图
使用:
- 创建视图:create view 视图名 as select 对外提供的内容 from 真实表名
- 删除视图:drop view 视图名
视图特点:
- 保护真实表,隐藏重要的字段的数据,保护数据
- 在视图中的操作会映射执行到真实表中
- 可以手动开启只读模式,使用关键字 with read only
注意:视图的创建必须拥有dba权限
create view stu as select sno,sname,sage from student;create view stu2 as select sno,sname,sage from student with read only;select * from stu;update stu set sname='maskwolf' where sno=1;select * from student;