Postgresql的序列

 作者:瀚高PG实验室 (Highgo PG Lab)

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值