sql 序列什么意思
Sequence is a feature supported by some database systems to produce unique values on demand. Some DBMS like MySQL supports AUTO_INCREMENT
in place of Sequence.
序列是某些数据库系统支持的功能,可以按需生成唯一值。 一些DBMS(例如MySQL)支持AUTO_INCREMENT
代替Sequence。
AUTO_INCREMENT
is applied on columns, it automatically increments the column value by 1
each time a new record is inserted into the table.
AUTO_INCREMENT
应用于列,每次将新记录插入表中时,列值都会自动增加1
。
Sequence is also some what similar to AUTO_INCREMENT
but it has some additional features too.
序列也与AUTO_INCREMENT
类似,但也具有一些其他功能。
创建一个序列 (Creating a Sequence)
Syntax to create a sequence is,
创建序列的语法是
CREATE SEQUENCE sequence-name
START WITH initial-value
INCREMENT BY increment-value
MAXVALUE maximum-value
CYCLE | NOCYCLE;
The initial-value specifies the starting value for the Sequence.
初始值指定序列的起始值。
The increment-value is the value by which sequence will be incremented.
增量值是将序列递增的值 。
The maximum-value specifies the upper limit or the maximum value upto which sequence will increment itself.
最大值指定序列将自行递增的上限或最大值。
The keyword
CYCLE
specifies that if the maximum value exceeds the set limit, sequence will restart its cycle from the begining.关键字
CYCLE
指定如果最大值超过设置的限制,则序列将从头开始重新开始其循环。And,
NO CYCLE
specifies that if sequence exceedsMAXVALUE
value, an error will be thrown.并且,
NO CYCLE
指定如果序列超过MAXVALUE
值,将引发错误。
在SQL查询中使用序列 (Using Sequence in SQL Query)
Let's start by creating a sequence, which will start from 1
, increment by 1
with a maximum value of 999
.
让我们从创建一个序列开始,该序列将从1
开始,以1
为增量,最大值为999
。
CREATE SEQUENCE seq_1
START WITH 1
INCREMENT BY 1
MAXVALUE 999
CYCLE;
Now let's use the sequence that we just created above.
现在,使用上面刚刚创建的序列。
Below we have a class table,
下面有一个类表,
ID | NAME |
---|---|
1 | abhi |
2 | adam |
4 | alex |
ID | 名称 |
---|---|
1个 | 阿比 |
2 | 亚当 |
4 | 亚历克斯 |
The SQL query will be,
SQL查询将是
INSERT INTO class VALUE(seq_1.nextval, 'anu');
Resultset table will look like,
结果集表如下所示:
ID | NAME |
---|---|
1 | abhi |
2 | adam |
4 | alex |
1 | anu |
ID | 名称 |
---|---|
1个 | 阿比 |
2 | 亚当 |
4 | 亚历克斯 |
1个 | 阿努 |
Once you use nextval
the sequence will increment even if you don't Insert any record into the table.
一旦使用nextval
,即使您没有在表中插入任何记录,序列也会递增。
sql 序列什么意思