1. 序列
什么是序列:一串连续的整数数字
默认的情况下,Oracle没有主键的自增长。使用序列来解决这个问题。
序列的作用:在Oracle中主要做为主键的自增长功能。
创建序列的语法:
create sequence 序列名
[start with // 起始值
increment by //步长
minvalue | maxvalue | nomaxvalue // 最小值,最大值,无限大小
cycle | nocycle // 是否循环使用
cache | nocache] //是否使用缓存
-- 创建一个序列名为seq_one,起始值为1,步长为2,最大值9,循环使用,不指定缓存
create sequence seq_one
start with 1
increment by 2
maxvalue 9
cycle
nocache;
序列的操作属性:
在序列中提供了以下的两种操作:
序列的属性 | 功能 |
---|---|
nextval | 得到序列的下一个值 |
currval | 得到序列当前的值 |
-- 查询当前的序列号
select seq_one.nextval 是否正确?
必须加上from关键字
疑问:dual是什么?
虚拟表,用来让select的语法完整
-- mysql查询现在的时间
select now();
-- 在oracle中使用sysdate
-- 注:oracle中只要使用select语句,语法必须包含from
-- 在oracle中有一个虚拟表名:dual,为了让select 语法完整
select sysdate from dual;
-- 查询序列
select seq_one.nextval from dual;
select seq_one.currval from dual;
注:刚创建的表 ,使用seq_one.currval获取当前序列会报错 ,因为刚创建的表没有当前序列,必须先获取下一个序列:seq_one.nextval,否则报错.
2. Oracle分页查询:伪列ROWNUM
伪列ROWNUM:
ROWNUM是Oracle数据库从数据文件中读取数据的顺序。它取得第一条记录则ROWNUM值为1,第二条为2,依次类推。如果你用>,>=,=,between…and这些条件,因为从表中得到的第一条记录的ROWNUM为1,不满足ROWNUM>5的条件则被过滤。接着取下条,它的ROWNUM还是1,又被过滤,依次类推便没有了数据。
解决方案:需要使用子查询将rownum以虚拟表的形式保存下来,再进行二次查询。
代码:
-- 分页查询
-- 每页显示5条
select * from emp;
-- 伪列rownum
select rownum, e.* from emp e;
-- 查询第1页
select rownum, e.* from emp e where rownum > 0 and rownum<=5;
-- 查询第2页
select rownum, e.* from emp e where rownum > 5;
-- rownum是对结果集进行编号
-- 将rownum做成一张虚拟表,再次查询
select t.* from (select rownum rn, e.* from emp e) t where rn>0 and rn<=5;
select t.* from (select rownum rn, e.* from emp e) t where rn>5 and rn<=10;
select t.* from (select rownum rn, e.* from emp e) t where rn>10 and rn<=15;