PostgreSQL SEQUENCE
发布时间:2020-12-13 17:20:23 所属栏目:百科 来源:网络整理
导读:PostgreSQL有数据类型 smallserial,serial,bigserial,它们都不是真正的类型,是依赖与一个序列的自动增长的且不为null的类型。 create table tb10( id serial ); 等价于下面的语句: create sequence tb10_id_seq; create table tb10( id integer not null
PostgreSQL有数据类型 smallserial,serial,bigserial,它们都不是真正的类型,是依赖与一个序列的自动增长的且不为null的类型。 create table tb10( id serial );
等价于下面的语句: create sequence tb10_id_seq;
create table tb10( id integer not null default nextval('tb10_id_seq');
);
alter seqence tb10_id_seq owner by tb10.id;
第三句的意思是创建的序列从属于tb10的id字段,这样删除id字段之后,该序列也会自动被删除。 NOTE:序列没有保证唯一或者主键,如果需要,需自行添加。 postgres=# insert into tb10(name) values('bb');
ERROR: duplicate key value violates unique constraint "tb10_pkey"
DETAIL: Key (id)=(1) already exists.
解释: postgres=# select * from tb10;
id | name ----+------
1 | a
2 | a
3 | a
4 | a
(4 rows)
postgres=# select currval('tb10_id_seq');
currval ---------
2
(1 row)
可以看到,表中id有值1,2,3,4,而序列的值还是2。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |