Postgresql的序列

来源:互联网 发布:淘宝网手工艺品 编辑:程序博客网 时间:2024/06/04 20:08

Postgresql中的序列作为数据类型存在,smallserial、serial和bigserial并不是真正的类型,只是为了创建唯一标识符而存在的符号。

创建序列的两种方式

1、直接在表中指定字段类型为smallserial、serial和bigserial。

CREATE table test(text varchar,serial1 serial);

INSERT into test VALUES('一');

INSERT into test VALUES('二');

INSERT into test VALUES('三');

INSERT into test VALUES('四');

mydb=# Select * from test;

 text | serial1

------+---------

 一   |       1

 二   |       2

 三   |       3

 四   |       4

(4 rows)

 

2、先创建序列名称,然后在新建表中指定相关列的属性,该列需要int类型。

序列创建语法

CREATE [ TEMPORARY | TEMP ] SEQUENCE name [ INCREMENT [ BY ] increment ]

    [ MINVALUE minvalue | NO MINVALUE ] [ MAXVALUE maxvalue | NO MAXVALUE ]

    [ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE ]

    [ OWNED BY { table.column | NONE } ]

例:

--创建一个步长为10,最小值为1,初始值为17,缓存为100,可循环的使用的序列

create sequence test_id_seq increment by 10 minvalue 1 no maxvalue start with 17 cache 100  cycle;

--查看序列的属性,两种方式,使用psql中\d查看,或直接查询序列名称

mydb=# \d test_id_seq

         Sequence "public.test_id_seq"

    Column     |  Type   |        Value       

---------------+---------+---------------------

 sequence_name | name    | test_id_seq

 last_value    | bigint  | 17

 start_value     | bigint  | 17

 increment_by | bigint  | 10

 max_value     | bigint  | 9223372036854775807

 min_value      | bigint  | 1

 cache_value  | bigint  | 100

 log_cnt           | bigint  | 0

 is_cycled        | boolean | t

 is_called         | boolean | f

 

mydb=# SELECT * from test_id_seq;

 sequence_name | last_value | start_value | increment_by |      max_value      | min_value | cache_value | log_cnt | is_cycled | is_called

---------------+------------+-------------+--------------+---------------------+-----------+-------------+---------+-----------+-----------

 test_id_seq   |       1007 |          17 |           10 | 9223372036854775807 |         1 |         100 |      32 | t         | t

(1 row)

 

--创建一个使用上述序列的表

create table test(wenzi varchar,id int4 not null DEFAULT nextval('test_id_seq'));

--为表中不使用序列的列插入数据

INSERT into test VALUES('一');

INSERT into test VALUES('二');

INSERT into test VALUES('三');

INSERT into test VALUES('四');

--查询插入后的数据

mydb=# select * from test;

 wenzi | id

-------+----

 一    | 17

 二    | 27

 三    | 37

 四    | 47

(4 rows)


原创粉丝点击