Oracle syntax (two: sequence, Oracle paging)

1. Sequence

What is a sequence: a string of consecutive integer numbers
By default, Oracle has no auto-increment of the primary key. Use sequence to solve this problem.
The role of sequence: In Oracle, it is mainly used as the self-growth function of the primary key .

Syntax to create a sequence:

create sequence sequence name
[start with // initial value
increment by // step
minvalue | maxvalue | nomaxvalue // minimum, maximum, unlimited size
cycle | nocycle // whether to use
cache circularly | nocache] // whether to use cache

-- 创建一个序列名为seq_one,起始值为1,步长为2,最大值9,循环使用,不指定缓存
create sequence seq_one 
start with 1
increment by 2
maxvalue 9
cycle
nocache;
Operational properties of the sequence:

The following two operations are provided in the sequence:

Sequence attributes Features
nextval Get the next value of the sequence
currval Get the current value of the sequence
-- 查询当前的序列号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;

Note: For the newly created table, using seq_one.currval to get the current sequence will report an error, because the newly created table does not have the current sequence, you must first get the next sequence: seq_one.nextval, otherwise an error will be reported.

2. Oracle paging query: pseudo column ROWNUM

Pseudo column ROWNUM:

        ROWNUM is the order in which the Oracle database reads data from the data file. It gets the first record and the ROWNUM value is 1, the second is 2, and so on. If you use >,>=,=,between...and these conditions, because the ROWNUM of the first record obtained from the table is 1, and the condition of ROWNUM>5 is not met, it will be filtered. Then remove the bar, its ROWNUM is still 1, and it is filtered, and so on, there is no data.
        Solution: You need to use a subquery to save rownum in the form of a virtual table, and then perform a second query. Insert picture description here
Code:

-- 分页查询
-- 每页显示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;

Guess you like

Origin blog.csdn.net/RookiexiaoMu_a/article/details/105129133